代码是这样的:
var name = 'outer';
var obj = {
name: 'obj',
foo: function (arg) {
this.run = arg;
this.run();
},
bar:function (arg) {
arg();
}
};
function fx() {
alert(this.name);
};
obj.foo(fx);//fx中的this指向obj,此时alert的结果是obj
obj.bar(fx);//这样调用fx中的this却指向当前作用域,alert的结果却是outer
就像
$(selector).on('click',function(){
//这里的this会指向被选中的标签,
//而希望通过这个回调函数来操作当前作用域中的一些属性时就要另想办法
});
所以,this的指向问题是在哪决定的?
fx的作用域是window。如果想输出'obj'的话可以:
bar:function (arg) {
arg().bind(this);
}
绑定obj的作用域
在一个函数上下文中,this由调用者提供,由调用函数的方式来决定。
obj.foo(fx)触发时,进入foo函数的执行上下文,此时this指向foo函数的调用者obj
obj.bar(fx)触发时,进入bar函数里的arg函数,也就是fx函数本身,此时的this指向全局作用域中fx的调用者window对象
详情参阅深入理解JavaScript系列(13):This? Yes,this!
this应该指向方法的所有者,foo方法中调用的已经是obj的run方法了