根据 MDN:The bind method
Calling
f.bind(someObject)
creates a new function with the same body and scope asf
, but where this occurs in the original function, in the new function it is permanently bound to the first argument ofbind
, regardless of how the function is being used:
function f() {
return this.a;
}
var g = f.bind({a: 'azerty'});
console.log(g()); // azerty
var h = g.bind({a: 'yoo'}); // bind only works once!
console.log(h()); // azerty
var o = {a: 37, f: f, g: g, h: h};
console.log(o.a, o.f(), o.g(), o.h()); // 37, 37, azerty, azerty
但是当我尝试下面的代码时:
var module = {
x: 42,
getX: function() {
return this.x;
}
}
var unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined
var boundGetX = unboundGetX.bind(module);
console.log(boundGetX()); // expected output: 42
module.x = 43;
boundGetY = boundGetX.bind(module);
console.log(boundGetY()); // shouldn't this be 42??
预期输出:
undefined
42
42
实际输出:
undefined
42
43
谁能给我解释一下吗?
最佳答案
这里的 module 是常量,但 module.x 不是。这就是您可以更改 module.x 值但不能更改模块的原因。
所以你改变的是模块的值,而不是模块本身。
关于javascript - 理解 JavaScript 中的 bind(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53827623/