Skip to content

setTimeout

ythy edited this page Sep 25, 2017 · 1 revision

The "this" problem

When you pass a method to setTimeout() (or any other function, for that matter), it will be invoked with a this value that may differ from your expectation.

Explanation

Code executed by setTimeout() is called from an execution context separate from the function from which setTimeout was called. The usual rules for setting the this keyword for the called function apply, and if you have not set this in the call or with bind, it will default to the global (or window) object in non–strict mode, or be undefined in strict mode. It will not be the same as the this value for the function that called setTimeout.

See the following example:

myArray = ['zero', 'one', 'two'];
myArray.myMethod = function (sProperty) {
    alert(arguments.length > 0 ? this[sProperty] : this);
};

myArray.myMethod(); // prints "zero,one,two"
myArray.myMethod(1); // prints "one"1234567

The above works because when myMethod is called, its this is set to myArray by the call, so within the function, this[sProperty] is equivalent to myArray[sProperty]. However, in the following:

setTimeout(myArray.myMethod, 1000); // prints "[object Window]" after 1 second
setTimeout(myArray.myMethod, 1500, '1'); // prints "undefined" after 

The myArray.myMethod function is passed to setTimeout, then when it's called, its this is not set so it defaults to the window object

Clone this wiki locally