函数中的this
指向问题
函数执行时,
若没有调用者如:fn()
,则函数里的this
就是window
对象;
若有调用者如:obj.fn()
,则函数里的this
就是调用者即obj对象
总结:谁调用函数(或方法),函数里的
this
就是谁,无明显调用者时,this
就是window注意:
obj.prop() 等同于 obj["prop"]()
var obj = { color: "coral", action: function(){ console.log(this.color); } } obj.action(); // "coral" obj["action"](); // "coral"
经典面试题
var length = 88;
function test(){
console.log(this.length);
}
var obj = {
length:99,
action:function(){
test(); // 88
arguments[0](); // 2
}
}
obj.action(test,[1,2,3]);