javascript setTimeout call error

左心房为你撑大大i 提交于 2019-12-03 13:59:02

Using call does not help here: it calls setTimeout with your this object, but the callback function itself is still called from the global scope. What you really want to do is something like this:

function foo() {
    var self = this;
    this.bar = function() {
        console.log("keep going");
        window.setTimeout(function() { self.bar(); }, 100);
    }
    this.bar();
}

Edit: If you really want something similar to the call approach, you can use bind which binds the this value for a function:

window.setTimeout(this.bar.bind(this), 100);

However, this is part of the new ECMAScript 5 spec which is not yet supported by all browsers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!