tags:

views:

34

answers:

2
function Something() {
  this.var1 = 0;
  this.var2 = 2;
  this.mytimer;
  this.getCars=function() {
    //some code
  };
  this.start = function(l) {
    this.updateTimer=setInterval("this.getCars();" , 5000);
  };
}

var smth = new Something();
smth.start();

When I type in this.getCars() it does not work. if the function is global declared and i put in for example just getCars it works. I don't know how to work out this problem because setInterval becomes as parameter a String.

Can somebody help me put with this?

+1  A: 
var me = this
setInterval(function() {me.getCars()}, 5000)

if you happen to be using prototype, you could also use the handy bind method:

setInterval(this.getCars.bind(this), 5000)
jspcal
I am using JQuery. Can you be more specific of how you mean to use the bind method?
Max
bind is optional, basically just an alternate way of doing it...
jspcal
I don't believe that jQuery has a `bind` equivalent.
Justin Johnson
A: 

Try this:

function Something() {
  this.var1 = 0;
  this.var2 = 2;
  this.mytimer;
  var me = this;
  this.getCars = function() {
    console.log(me.var2);
  };
  this.start = function(l) {
    me.updateTimer = setInterval(me.getCars, 1000);
  }
}

var smth = new Something();
smth.start();

The console.log() bit is Firefox/Firebug. Replace it with something else if you're not using that (although I would highly recommend developing with it).

Basically the problem is that when you call a function, even a method of an object, the way you call it determines the value of this. See Method binding for more details. So what you do is fix the value of this as I've done in the above example (for methods).

cletus
Actually, since this.getCars is resolved to a function reference when setInterval is called, setInterval(this.getCars,1000) will also work fine. The problem is using 'this' in the getCars method. That is where using the 'me' var is really useful.
slebetman