Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'this' concept in the object in javascript

Tags:

javascript

I am sorry for that the simple question first. But I just want to know what happen in the code below.

var indexobj = {
    test : 1,
    testFunction : function() {
        document.getElementById('AA').innerHTML = indexobj.test++;
        //this is i wanted
        document.getElementById('BB').innerHTML = this.test++;
        //NaN
        setTimeout(indexobj.testFunction,1000);
    },
}
setTimeout(indexobj.testFunction,1);

Here is the sample link below

http://jsfiddle.net/apss/JR5Xk/28/

Why in this example the ‘this’ inside the ‘testFunction’ function doesn’t mean ‘indexobj’ this object? Thanks for your help.

like image 513
apss1943 Avatar asked Jan 10 '23 03:01

apss1943


1 Answers

Because setTimeout runs callback function in global object context, meaning that indexobj.testFunction is invoked with this being a window object.

So you can either do

setTimeout(function() {
    indexobj.testFunction();
},1000);

or using Function.prototype.bind to create wrapper function with correct context:

setTimeout(indexobj.testFunction.bind(indexobj), 1000);

Another modern option from ES2015 is to use arrow function that preserves lexical context:

setTimeout(() => indexobj.testFunction(), 1000);
like image 80
dfsq Avatar answered Jan 19 '23 02:01

dfsq