JavaScript中的this机制
JavaScript有自己的一套this机制,在不同情况下,this的指向也不尽相同。
全局范围
console.log(this);//全局变量
全局范围使用this指向的是全局变量,浏览器环境下就是window。
注:ECMAScript5的strict模式不存在全局变量,这里的this是undefined。
函数调用中
functionfoo(){ console.log(this); } foo();//全局变量
函数调用中的this也指向全局变量。
注:ECMAScript5的strict模式不存在全局变量,这里的this是undefined。
对象方法调用
vartest={ foo:function(){ console.log(this); } } test.foo();//test对象
对象方法调用中,this指向调用者。
vartest={ foo:function(){ console.log(this); } } vartest2=test.foo; test2();//全局变量
不过由于this的晚绑定特性,在上例的情况中this将指向全局变量,相当于直接调用函数。
这点非常重要,同样的代码段,只有在运行时才能确定this指向
构造函数
functionFoo(){ console.log(this); } newFoo();//新创建的对象 console.log(foo);
在构造函数内部,this指向新创建的对象。
显式设置this
functionfoo(a,b){ console.log(this); } varbar={}; foo.apply(bar,[1,2]);//bar foo.call(1,2);//Number对象
使用Function.prototype的call或者apply方法是,函数内部this会被设置为传入的第一个参数。