使用绑定函数两次

thi*_*moe 3 javascript bind

在\n[MDN][绑定]

\n\n

我们看到这样的代码

\n\n
this.x = 9;    // this refers to global "window" object here in the browser\nvar module = {\n  x: 81,\n  getX: function() { return this.x; }\n};\nmodule.getX(); // 81\nvar retrieveX = module.getX;\nretrieveX();   \n// returns 9 - The function gets invoked at the global scope\nvar boundGetX = retrieveX.bind(module);\nboundGetX();\n
Run Code Online (Sandbox Code Playgroud)\n\n

YES\xef\xbc\x8c我知道绑定会改变“this”值,但我混淆了下面的代码

\n\n
var demo=boundGetX.bind(this);// or boundGetX.bind(window);\ndemo();// still 81\n
Run Code Online (Sandbox Code Playgroud)\n\n

再次使用绑定,我认为它会将“this”指向“窗口”,但事实并非如此。\n我想知道为什么。

\n

dec*_*eze 6

bind 返回一个新函数,该函数在调用时保持原始函数的上下文不变。本质上它是这样做的:

function bind(originalFunction, context) {
    return function () {
        originalFunction.call(context);
    };
}
Run Code Online (Sandbox Code Playgroud)

无论您如何调用该绑定函数或对其执行其他操作,originalFunction都将在特定上下文中进行调用。您可以重新绑定该绑定函数,这将返回另一个新函数,但这不会影响“内部包装”的原始函数和上下文。