2

I need to pass a reference to the current object into an anonymous function. In Mootools it would be something like this:

 this.start = function(){ this.intervalId = setInterval(function(){ this.elapsedTime ++; this.setTime(); }.bind(this), 1000); } 

But I need it to be done using jQuery and such syntax is not supported in jQuery. What can I do? I tried:

 this.start = function(){ var thisObj = this; this.intervalId = setInterval(function(){ thisObj.elapsedTime ++; thisObj.setTime(); }, 1000); } 

But it looks like thisObj is simply a new object because some of its methods which were assigned values in the init method are now empty.

Please advise :)

1
  • No, this should work. Please create a jsfiddle.net demo. It could depend on how you call start. Commented May 26, 2011 at 16:02

2 Answers 2

4

Your code should work, thisObj does not reference a new object. It references this. If this code does not work, it means that you are not calling start() correctly and even bind() would not help you here.

So you have to fix your code first, make sure you are calling start() the right way, like myobj.start().

But in any case, jQuery provides the $.proxy method:

this.intervalId = setInterval($.proxy(function(){ this.elapsedTime ++; this.setTime(); }, this), 1000); 

which does the same as .bind().

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I now have this: console.log(this.timerInputs.hours); this.intervalId = setInterval($.proxy(function(){ console.log(this.timerInputs.hours); this.elapsedTime ++; this.setTime(); }, this), 1000); This is a script for a timer so the this.timerInputs.hours is an input object for hours. The thing is that console.log(this.timerInputs.hours); before setInterval return a valid object but right after setInterval it returns an empty object
1

change thisObj to a global so it exists outside of your start function. The way you had it the setInterval function call wouldn't know what thisObj was

var thisObj = null; this.start = function(){ thisObj = this; this.intervalId = setInterval(function(){ thisObj.elapsedTime ++; thisObj.setTime(); }, 1000); } 

working example: http://jsfiddle.net/hunter/Swh9U/


And to prove Felix's point, OP's code does work: http://jsfiddle.net/hunter/Swh9U/1/

1 Comment

The OP's code should work. Lifting the variable in a higher scope should not make a difference. The function passed to setInterval is a closure which has access to the variables defined inside start.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.