从异步函数访问时未定义的函数

时间:2017-10-28 12:20:09

标签: javascript

我不明白,为什么当我将一个函数设置为一个对象实例时,无论何时从异步中访问它,比如setTimeout或者promise,它都是未定义的。有人可以解释一下吗?有解决方法吗?

由于

function Animal() {
    this.check = function () {
        writeln(typeof this.test);
    }
    setTimeout(this.check, 1000); // returns undefined
}

var animal = new Animal();
animal.test = function () {

}
animal.check(); // returns function

1 个答案:

答案 0 :(得分:0)

因为你在这里失去了背景:

setTimeout(this.check, 1000);

因此,this内的check将为window,其中没有test属性。也许这样做:

setTimeout(this.check.bind(this), 1000);

旁注:动态分配功能是一种性能杀手,因此风格很差。总有更好的方法......

相关问题