Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
66
rated 0 times [  69] [ 3]  / answers: 1 / hits: 19075  / 13 Years ago, sat, october 29, 2011, 12:00:00

I have a class like:



function run(){
this.interval;
this.start = function(){
this.interval = setInterval('this.draw()',1000);
};
this.draw = function(){
//some code
};} var run = new run(); run.start();


however I can't seem to reference/call this.draw() within the setInterval, it says this.draw() is not a function, and if I remove the quotes it says useless setInterval call, what am I doing wrong?


More From » scope

 Answers
1

The value of this is set depending on how a function is called. When you call a function as a constructor using new then this will refer to the object being created. Similarly when you call a function with dot notation like run.start() then this will refer to run. But by the time the code run by the setInterval is called this doesn't mean what you think. What you can do is save a reference to this and then use that reference, like the following:



function Run(){
var self = this;

self.start = function(){
self.interval = setInterval(function() { self.draw(); },1000);
};

self.draw = function(){
//some code
};
}

var run = new Run();

run.start();


Note also that you've created a function called run and a variable called run - you need to give them different names. In my code (bearing in mind that JS is case sensitive) I've changed the function name to start with a capital R - which is the convention for functions intended to be run as constructors.



EDIT: OK, looking at the other answers I can see that just maybe I overcomplicated it and as long as draw() doesn't need to access this it would've been fine to just say:



this.interval = setInterval(this.draw, 1000);


But my point about not giving your constructor and later variable the same name still stands, and I'll leave all the self stuff in because it is a technique that you will need if draw() does need to access this. You would also need to do it that way if you were to add parameters to the draw() function.


[#89377] Friday, October 28, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
danae

Total Points: 26
Total Questions: 97
Total Answers: 112

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;