Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

setTimeout and "this" in JavaScript

I have a method that uses the setTimeout function and makes a call to another method. On initial load method 2 works fine. However, after the timeout, I get an error that says method2 is undefined. What am I doing wrong here?

ex:

test.prototype.method = function()
{
    //method2 returns image based on the id passed
    this.method2('useSomeElement').src = "http://www.some.url";
    timeDelay = window.setTimeout(this.method, 5000);
};

test.prototype.method2 = function(name) {
    for (var i = 0; i < document.images.length; i++) {
        if (document.images[i].id.indexOf(name) > 1) {
            return document.images[i];
        }
    }
};
question from:https://stackoverflow.com/questions/591269/settimeout-and-this-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue is that setTimeout() causes javascript to use the global scope. Essentially, you're calling the method() class, but not from this. Instead you're just telling setTimeout to use the function method, with no particular scope.

To fix this you can wrap the function call in another function call that references the correct variables. It will look something like this:

test.protoype.method = function()
{
    var that = this;

    //method2 returns image based on the id passed
    this.method2('useSomeElement').src = "http://www.some.url";

    var callMethod = function()
    {
        that.method();
    }

    timeDelay = window.setTimeout(callMethod, 5000);
};

that can be this because callMethod() is within method's scope.

This problem becomes more complex when you need to pass parameters to the setTimeout method, as IE doesn't support more than two parameters to setTimeout. In that case you'll need to read up on closures.

Also, as a sidenote, you're setting yourself up for an infinite loop, since method() always calls method().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...