最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

scope - javascript setTimeout call error - Stack Overflow

programmeradmin4浏览0评论

I want to invoke the window.setTimeot function with my custom scope so I use the call method, but there is something wrong.

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

new foo;

under Firefox this prints to the console only 1 line and then nothing, and under google chrome it throws a TypeError.

What is the problem in my code?

I want to invoke the window.setTimeot function with my custom scope so I use the call method, but there is something wrong.

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

new foo;

under Firefox this prints to the console only 1 line and then nothing, and under google chrome it throws a TypeError.

What is the problem in my code?

Share Improve this question asked May 24, 2011 at 14:48 Gergely FehérváriGergely Fehérvári 7,9516 gold badges52 silver badges77 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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.

发布评论

评论列表(0)

  1. 暂无评论