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?
The value of
thisis set depending on how a function is called. When you call a function as a constructor usingnewthenthiswill refer to the object being created. Similarly when you call a function with dot notation likerun.start()thenthiswill refer torun. But by the time the code run by thesetIntervalis calledthisdoesn’t mean what you think. What you can do is save a reference tothisand then use that reference, like the following:Note also that you’ve created a function called
runand a variable calledrun– 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 accessthisit would’ve been fine to just say:But my point about not giving your constructor and later variable the same name still stands, and I’ll leave all the
selfstuff in because it is a technique that you will need ifdraw()does need to accessthis. You would also need to do it that way if you were to add parameters to thedraw()function.