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 🙂
Your code should work,
thisObjdoes not reference a new object. It referencesthis. If this code does not work, it means that you are not callingstart()correctly and evenbind()would not help you here.So you have to fix your code first, make sure you are calling
start()the right way, likemyobj.start().But in any case, jQuery provides the
$.proxymethod:which does the same as
.bind().