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?
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?
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);
this depends on the invocation 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 invocation.
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.