0

How can I keep the this reference when I use timeOut?

var o = {
   f:function(){
     console.log(this)
     setTimeout(this.f,100);
     }
}
o.f();

When I run this code the this reference is wrong ... what am I missing?

2 Answers2

0

You can pass paramters into setTimeout, as a third parameter. That way you can pass a reference.

However, if you are trying to create some "object oriented" stuff with new, you shall use a function instead as this:

function obj() {
  this.publicFunction = function() {
    console.log("I'm public!");
  };
  var privateFunction = function() {
    console.log("Only accessible from inside this instance!");
  }
}

var objInstance = new obj();
objInstance.publicFunction(); // Logs w/o problem
objInstance.privateFuntion() // Undefined!

EDIT (again): But if you're really keen to use a object for some reason, this in a object, actually references to the object itself. But since the object is defined as a variable (and in your case global as well), one could directly refer to the name instead of this. Here:

var o = {
  f: function() {
    console.log(this);  // Will log the object 'o'
    console.log(o);  // Same as above
  }
};

setTimeout(o.f, 100);
Eric
  • 18,532
  • 2
  • 34
  • 39
  • Yeah I just remembered.. however, I think OP is out for something "object oriented", which I edited and added an example for. – Eric Jul 01 '13 at 14:24
  • I believe there are compatibility issues in passing additional arguments into setTimeout, but I don't know the details. Alternate solutions are using a closure, or Function.prototype.bind – bfavaretto Jul 01 '13 at 14:34
0

depends on the method. For more details see my other stackoverflow answer.
f() is a member of o, but o.f is a function passed to timeout and called with functional . This will give you the desired results.

var o = {
   f:function(){
     console.log(o)
     setTimeout(o.f,100);
     }
}
o.f();

Here is another example of member function called with functional invocation: See my Fiddle

var anObject = {
    test: function(isThis, message) {
        if(this === isThis) 
            console.log("this is " + message);
        else
            console.log("this is NOT " + message);
    }//I am a method
};

//method invocation
anObject.test(anObject, "anObject"); //this is anObject

var aFunction = anObject.test;
//functional invocation
aFunction(anObject, "anObject with aFunction"); //this is NOT anObject with aFunction
aFunction(this, "global with aFunction");//this is global with aFunction

Hope this helps.

Community
  • 1
  • 1
Mke Spa Guy
  • 793
  • 4
  • 13