在\n[MDN][绑定]
\n\n我们看到这样的代码
\n\nthis.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();\nRun Code Online (Sandbox Code Playgroud)\n\nYES\xef\xbc\x8c我知道绑定会改变“this”值,但我混淆了下面的代码
\n\nvar demo=boundGetX.bind(this);// or boundGetX.bind(window);\ndemo();// still 81\nRun Code Online (Sandbox Code Playgroud)\n\n再次使用绑定,我认为它会将“this”指向“窗口”,但事实并非如此。\n我想知道为什么。
\nbind 返回一个新函数,该函数在调用时保持原始函数的上下文不变。本质上它是这样做的:
function bind(originalFunction, context) {
return function () {
originalFunction.call(context);
};
}
Run Code Online (Sandbox Code Playgroud)
无论您如何调用该绑定函数或对其执行其他操作,originalFunction都将在特定上下文中进行调用。您可以重新绑定该绑定函数,这将返回另一个新函数,但这不会影响“内部包装”的原始函数和上下文。