javascript 的绑定方法似乎没有按预期工作

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();

代码结果是log out the global or window,我想知道为什么bind方法没有绑定'this'到obj对象上下文?

您正在立即调用函数。删除 say 函数后面的括号。如果您希望在没有两个连续括号 obj.say()() 的情况下调用该函数,请使用 .call() 而不是 .bind()

var obj = {
  say: function() {
    function _say() {
      console.log(this);
    }
    return _say.call(this);
  }
};

obj.say();

在赋值过程中,变量obj仍然没有任何值。因此,您对 bind 的调用等同于 .bind(undefined),其行为与您观察到的方式相同。

更具体地说,this 引用 window 是因为 OrdinaryCallBindThis 执行了以下步骤(非严格模式):

[...]
If thisArgument is undefined or null, then
[...]
Let thisValue be globalEnvRec.[[GlobalThisValue]].

您可以在 chrome 调试器中检查 [[BoundThis]] 在您调用后确实 undefined