gpt4 book ai didi

javascript - 理解 JavaScript 中的 bind()

转载 作者:行者123 更新时间:2023-11-30 11:10:47 25 4
gpt4 key购买 nike

根据 MDN:The bind method

Calling f.bind(someObject) creates a new function with the same body and scope as f, but where this occurs in the original function, in the new function it is permanently bound to the first argument of bind, 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com