参考文章:https://www.cnblogs.com/hammerc/p/7390424.html
这是因为this是那个调用他的对象,而setTimeout之后调用它的那个对象变成window了
function Test() {
this.num = 100;
this.func = function(){
console.log(this.num); // 100
setTimeout(function(){
console.log(this.num); // undefined
}, 500);
};
}
var obj = new Test();
obj.func();//100 undefind
不使用匿名函数的话要这样写
function Test() {
this.num = 100;
this.func = function(){
console.log(this.num); // 100
var that = this;
setTimeout(function(){
console.log(that.num); // 100
}, 500);
};
}
var obj = new Test();
obj.func();