Search code examples
javascriptthisbindiife

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?


Solution

  • 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.