Re: 'this' and setInterval
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.javascript archive

Re: 'this' and setInterval

From: VK <schools_ring@yahoo.com>
Date: Fri Nov 18 2005 - 15:16:50 CET

Andrew Poulos wrote:
> If I have some code that's a bit like this
>
> Con = function() {
> this.op = 1;
> this.count = 0;
> }
> Con.prototype.loop = function() {
> this.doNext = setInterval(this.next, 100);
> }
> Con.prototype.next = function() {
> this.count++;
> if (this.count > 10) clearInterval(this.doNext);
> }
>
> obj = new Con();
>
> when I call obj.loop(); 'this' in obj.next refers to setInterval
> and not obj . I realise I can add var ref = this; and send it with
> setInterval but is there something I can do to get 'this' to refer to
> obj when in obj.next ?

Besides closures you can also overload your function. I'm not saying
it's anyhow better than closures, just another way:

function Con() {

 this.counter = 0;
 this.timerID = null;

 this.moveNext = function() {
  with (arguments.callee.context) {
   counter++;
   if (counter > 10) {
    clearInterval(timerID);
    alert('Show is over');
   }
  }
 }

 this.startLoop = function() {
  this.moveNext.context = this;
  this.timerID = self.setInterval(this.moveNext, 100);
 }
}

obj = new Con();
obj.startLoop();
Received on Mon Nov 21 03:33:49 2005