'this' concept in object in javascript

I apologize for this simple question. But I just want to know what happens 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);

Below is an example link

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

Why in this example the this function inside the testFunction does not mean "indexobj this object? Thanks for the help.

+4
source share
2 answers

Because it setTimeoutruns the callback function in the global object context , which means it indexobj.testFunctionis called with the thisbeing the windowobject.

So you can do

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

or using Function.prototype.bindto create a wrapper function with the correct context:

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

ES2015 , :

setTimeout(() => indexobj.testFunction(), 1000);
+6

, :

  • .

, .

:

setTimeout(indexobj.testFunction,1000);

, indexobj.testFunction, setTimeout. , , ( ) undefined .

: , indexobj :

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

bind, dfsq.

ES6 , , ...

+3

Source: https://habr.com/ru/post/1570430/


All Articles