var x = 1
var obj = {
x:2,
y:function(){
console.log(this.x)
}
}
setTimeout(obj.y,1000)
谁调用它,this就指向谁。上面例子是 setTimeout 函数调用了 obj.y 方法,而setTimeout 属于 window。
var num = 0
function Obj(){
this.num = 1
this.getNum = function(){
console.log(this.num)
}
this.getNumLater = function(){
setTimeout(function(){
console.log(this.num)
},1000)
}
}
var obj = new Obj
obj.getNum() //obj.num 1
obj.getNumLater() //window.num 0
会出现什么问题
为什么要用 var that = this
文章链接