Functions don't have their own this
, it is decided by the caller.
If you do myObject.daFunc()
that will be myObject
.
If you do var x = myObject.daFunc; x();
it will not be something useful.
If you do myObject.daFunc.apply(somethingElse)
it will be somethingElse
.
I think where the confusion comes from is that the this
inside of the function is unrelated to the this
in the scope that defined the function. So in that way, the function does have its own this
.
var myObject = {
foo: "bar",
dafunc: function() {
setTimeout(function(){
// now we lost "this", this doesn't work
console.log("dafunc: this.foo = " + this.foo);
}, 0);
}
};
This is where the "fat-array" syntax that some versions of Javascript have comes in. Here this
carries over from the defining scope:
setTimeout( () => {
// fat array "preserves" this
console.log("dafunc: this.foo = " + this.foo);
}, 0);