Reputation: 37
var obj = {
say: function() {
function _say() {
console.log(this);
}
return _say.bind(obj);
}()
};
obj.say();
the code result is log out the global or window, I want to know why the bind method doesn't bind 'this' to the obj object context?
Upvotes: 3
Views: 326
Reputation: 5195
During assignment the variable obj
still does not have any value. As such, your call to bind is equivalent to .bind(undefined)
which behaves the way you observed.
To be more specific, this
referring to window
is because of OrdinaryCallBindThis doing the following steps (non strict mode):
[...]
If thisArgument is undefined or null, then
[...]
Let thisValue be globalEnvRec.[[GlobalThisValue]].
You can check in the chrome debugger that [[BoundThis]]
is indeed undefined
after your call.
Upvotes: 1
Reputation: 1
You are invoking the function immediately. Remove parenthesis following say
function. If you are expecting to call the function without two consecutive parenthesis obj.say()()
use .call()
instead of .bind()
var obj = {
say: function() {
function _say() {
console.log(this);
}
return _say.call(this);
}
};
obj.say();
Upvotes: 0