【发布时间】:2017-08-28 17:51:28
【问题描述】:
在使用 bind() 函数时,我遇到了一种我目前不知道的情况。 有人可以给我解释一下为什么这个例子是这样工作的吗? 显然,传递给绑定函数的内联对象仅在第一次迭代中初始化,然后保留引用。 我找不到有关此的任何文档,如果您能指出正确的方向,我将不胜感激:-)
class test {
addLetter(element) {
console.log('addLetter', this.str);
this.str += element + ',';
}
foo() {
let arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
arr.forEach(this.addLetter.bind({
str: ''
}));
}
}
let a = new test();
a.foo();
OUTPUT:
addLetter
addLetter a,
addLetter a,b,
addLetter a,b,c,
addLetter a,b,c,d,
addLetter a,b,c,d,e,
addLetter a,b,c,d,e,f,
【问题讨论】:
-
你的代码可以解构为
let cb = this.addLetter.bind({...}); arr.forEach(cb);。 – 是的,您只使用一个绑定对象创建 one 回调。 -
确实,我的错误是将 forEach 视为正常循环,谢谢。
标签: javascript function.prototype