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.
Because it setTimeoutruns the callback function in the global object context , which means it indexobj.testFunctionis called with the thisbeing the windowobject.
setTimeout
indexobj.testFunction
this
window
So you can do
setTimeout(function() { indexobj.testFunction(); },1000);
or using Function.prototype.bindto create a wrapper function with the correct context:
Function.prototype.bind
setTimeout(indexobj.testFunction.bind(indexobj), 1000);
ES2015 , :
setTimeout(() => indexobj.testFunction(), 1000);
, :
.
, .
:
setTimeout(indexobj.testFunction,1000);
, indexobj.testFunction, setTimeout. , , ( ) undefined .
: , indexobj :
setTimeout(function(){indexobj.testFunction()}, 1000);
bind, dfsq.
ES6 , , ...
Source: https://habr.com/ru/post/1570430/More articles:Magento Session Not Updating in Event Observer - phpAndroid build failed. Com.android.dex.DexException: multiple dex files define Landroid / support - javaQt 5.4 application can be debugged in pre win7 - c ++using divide & conquer improves time complexity to find max and min in an array - algorithmhttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1570429/how-do-i-use-dtos-to-consume-a-rest-api-in-php&usg=ALkJrhjBuMlb7mw9jJ3TnusOet1pXlCffwAnsible: simulating a past when module - moduleSame width and height of container as image loading - jquerySort div in alphabetical order using data attribute - javascriptUL takes up full width without set width - cssWhat is the difference between RollingFile and RollingRandomAccessFile in log4j2 configuration - log4j2All Articles