Reputation: 4293
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.
http://jsfiddle.net/cgoddard/yQDLe/20/
Upvotes: 0
Views: 74
Reputation: 80744
When you write this.doDelayed
inside a doubly nested function, the this
keyword doesn't refer to your test
object. Instead, it refers to whatever object the currently executing function was called for, which is probably window
.
To overcome this, you have to save your this
in the very beginning of the test
function, 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 symbol x
is treated like a property on the window
object (also known as "global variable"). Therefore, both your doDelayed
and construct
functions end up on the window
object. 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 $this
is your saved value of this
from above), and do similarly for construct
.
Upvotes: 2