Reputation: 157
Let see code first
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()());
the result is "The Window"
;
I want to know what happend in every step.
I think this
is point to the object which call this function; right?
But why in this case this
is window
Upvotes: 1
Views: 70
Reputation: 48761
The second function invocation doesn't take place from the context of an object, but rather from the function returned from the first invocation.
Because there's no object context, the this
value becomes the default window
just like any other function.
// v-----------------v------function has context
alert(object.getNameFunc()());
// -----------^----second function was returned from the first
// and invoked so there's no object context
If we instead assigned the returned function to object
, then invoked it from that context, this
would then be a reference to object
.
obj.foo = object.getNameFunc();
obj.foo(); // "My Object"
Same exact function, but now it's being invoked from as a property of object
, which implicitly sets its this
value to object
.
The rules of this
are really pretty simple and easy to understand, but may not be what you'd expect at first.
The this
value is very dynamic, and is based entirely on how a function is invoked.
foo(); // 'this' is 'window'
object.foo(); // 'this' is 'object'
foo.call(object); // 'this' is 'object'
foo.apply(object);// 'this' is 'object'
var bar = foo.bind(object);
bar(); // 'this' is 'object'
So you can see that the default is window
when the function is invoked without any sort of connection to another object.
But when we call the function as a property of an object, this
suddenly refers to that object.
Or we can use .call
, .apply
or .bind
to manually set the this
value of the function call.
Upvotes: 1
Reputation: 324650
Since it's a new closure, the meaning of this
is lost. this
has always been a tricky thing to deal with, so I prefer to always start such a function with var that = this
to ensure that the meaning is not lost within closures.
Upvotes: 1