JavaScript中的匿名函数

参考文章: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();

猜你喜欢

转载自blog.csdn.net/m0_37456764/article/details/84873331