Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
36
rated 0 times [  38] [ 2]  / answers: 1 / hits: 40753  / 13 Years ago, tue, may 31, 2011, 12:00:00

I have some javascript code (within an object) :



toggle: function() {
var me = this;
var handler = function() { me.progress() };
me.intervalId = setInterval(handler, me.intervalTime);
//...More code
}


I'm kind of new to javascript, so doing the above as far as I can tell actually passes the me variable into anonymous the function. I was wanting to see if there is a more declarative way to do so? I wanted something along the line of:



var handler = (function(o) { o.progress();})(this));


but that doesn't seem to be working... Am I missing something? Is this a case where this is the way the language works so just declare a local variable and deal with it?



UPDATE:



The source to my problem was/is my unclear understanding of scope and closures in javascript. I found this article to help me understand a little more.


More From » javascript

 Answers
52

You can use .bind():



var handler = function() { this.progress(); }.bind(this);


New browsers have bind(), and the Mozilla docs have a solid implementation you can use to patch older browsers.


[#91955] Monday, May 30, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emerymariamm

Total Points: 276
Total Questions: 97
Total Answers: 99

Location: Comoros
Member since Sun, Dec 13, 2020
4 Years ago
emerymariamm questions
Fri, Mar 4, 22, 00:00, 2 Years ago
Wed, Jan 12, 22, 00:00, 2 Years ago
Sun, Jul 4, 21, 00:00, 3 Years ago
Wed, Dec 23, 20, 00:00, 4 Years ago
;