I have a javascript class object that I want to use multiple times on the same page, and it requires a setTimeout function to work as it keeps ticking over in the background. However, as you can see in this fiddle, on the timeout call, its only referencing the newest instance of the object. Does anyone know how I can sort it? Preferably, I would like to see how it is done not in jQuery, I like to understand exactly how it does it.
I have a javascript class object that I want to use multiple times on
Share
When you write
this.doDelayedinside a doubly nested function, thethiskeyword doesn’t refer to yourtestobject. Instead, it refers to whatever object the currently executing function was called for, which is probablywindow.To overcome this, you have to save your
thisin the very beginning of thetestfunction, say like this:var $this = this;Then you can refer to that very object using
$this.Besides this, when you write simply
x = something, the symbolxis treated like a property on thewindowobject (also known as “global variable”). Therefore, both yourdoDelayedandconstructfunctions end up on thewindowobject. Consequently, when you do this second time, they both get overwritten. This is why you get same results twice.Instead, you should write
$this.doDelayed = function() ...(where$thisis your saved value ofthisfrom above), and do similarly forconstruct.