使用setTimeout时绑定丢失

时间:2017-10-11 21:56:53

标签: javascript this call bind apply

我们假设我有这个代码

function UselessDelay() {
    this.petalCount = Math.floor(Math.random() * 12) + 1;
}

UselessDelay.prototype.declare = function () {
    console.log('I am a beautiful flower with ' + this.petalCount + ' petals!');
};

var ud = new UselessDelay();
ud.start();

其中start方法可以使用call或bind方法以不同方式编写:

UselessDelay.prototype.start = function () {
    var self = this;
    window.setTimeout(function () {
        self.declare.call(self);
    }, 3000);
};

UselessDelay.prototype.start = function () {
    window.setTimeout(this.declare.bind(this), 3000);
};

我对这些例子非常好,并且理解它们。让我们看看另一个启动方法

UselessDelay.prototype.start = function () {
    window.setTimeout(this.declare, 3000);
};

此功能的结果在3秒后触发,没关系。但是为什么这个“petalCount”属性是未定义的,但是对“declare”函数的引用工作得很好?

当this.declare执行作为参数传递给setTimeout函数时,会发生另一种奇怪的行为。

UselessDelay.prototype.start = function () {
    window.setTimeout(this.declare(), 3000);
};

此功能不会等待3个secons。它立即执行,但“petalCount”并未定义。我假设传递和调用函数有点在执行时打破了setTimeout函数,因此它保持不变。

0 个答案:

没有答案