javascript中的this关键字是个很令人头疼的问题,学习的时候也是个难点,觉得这个东西很玄乎,很乱;
下面是我个人的一点观点:
首先我们来看看直接定义的全局函数:
function introduce() {
alert("Hello, I am limeng");
}
这个函数的this指向谁呢?
定义在全局的函数,其实也就是window对象的一个方法,函数的所有者就是当前页面,也就是window对象,我们alert一下看看:
var name = "Hello, I am limeng";
function introduce() {
alert(this.name);
}
window.onload = introduce;
/*out:
*Hello, I am limeng
*/
我们在alert一下:
var name = "Hello, I am limeng";
function introduce() {
alert(this.name);
}
alert(window.introduce);
/*out:
*function introduce() {
* alert(this.name);
*}
*/
很显然,跟我们预期的一样。
下面我们看看事件处理函数:
<input id="name" type="button" value="limeng" />
function showValue() {
alert(this.value);
}
window.onload = function(){
document.getElementById('name').onclick = showValue;
}
/*out:
*limeng
*/
此时的全局函数中的this为什么不是window了呢?
其实在对onclick绑定的时候, 其实是对id为name的输入框Dom对象的onclick属性的赋值。而onclick的所有者就是这个dom对象。
再看:
function showValue() {
alert(this.value);
}
window.onload = function(){
document.getElementById('name').onclick = showValue;
alert(document.getElementById('name').onclick);
}
/*out:
*function showValue() {
* alert(this.value);
*}
*/
所以,当事件触发的时候,就会去调用name按钮的onclick方法,,这个时候this关键字自然就指向的是name按钮了。
即:对象的方法中this指的就是该对象。
再看:
<input id="name" type="button" value="limeng" onclick="showValue();" />
此处出错了,为什么呢?
因为这个时候并不是赋值,而是引用。我们弹出一下onclick看看:
alert(document.getElementById('name').onclick);
/*out:
*function onclick() {
* showValue();
*}
*/
应该能明目为什么会了吧。
而对于不是事件处理函数的场合,我们可以使用apply,或者call,来改变this关键字的指向。
不过本人目前对apply和call了解的还不够多。简单说一个例子吧:
var limeng = {
name : 'limeng',
age : 26
};
function introduce() {
alert(this.name);
}
introduce.call(limeng);