smallbone
smallbone

Reputation: 37

The bind method of javascript seems not working as expected

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

Answers (2)

ASDFGerte
ASDFGerte

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

guest271314
guest271314

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

Related Questions