this
- 谁调用指向谁
- 没有调用指向widow
- 看谁调用是看最后执行的是谁
补充: 在严格版中的默认的this不再是window,而是undefined
var o = {
a:10,
b:{
a:12,
fn:function(){
console.log(this.a); //undefined
console.log(this); //window
}
}
}
var j = o.b.fn;
j();
// 赋值给j再来执行,那么就指向window了。
// o.b.fn() 如果这样执行,this就指向b
注意:在setTimeOut、setInterval里面使用this时是指向window的。
所以使用时
- 可以使用箭头函数
function a (){
setTimeOut(()=>{
console.log(this);
},1000);
}
- 或者在函数保存this,再使用。
function a (){
var that = this;
setTimeOut(function (){
console.log(that);
},1000)
}