javascript - 理解 JavaScript 中的 bind()

标签 javascript ecmascript-5 ecma

根据 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/

相关文章:

javascript - Ember 模型结果在模板中为空,但在检查器中已填充

javascript - 在动态添加的表行上添加 onclick 函数

javascript - 如何停止 Javascript forEach?

javascript - "~"(代字号)在 import ... from "~/"中意味着什么

regex - ECMAScript 正则表达式是否匹配其语法字符?

javascript - jQuery Datatable on click tr 函数多次触发

javascript - 如何添加点击jQuery函数的回调?

javascript - Ecmascript 5.1 中哪里提到 if 语句中不接受左大括号?

javascript - 将 npm 与 Vanilla js 一起使用

javascript - 如何为特定节点编写条件 xpath 选择?