![](/img/trans.png)
[英]Adding two different classes to one function at a different time javascript
[英]Two classes one with reference to function to another different this value
我有问题,我不知道如何解决:
this.bWords.push(word);
^
类型错误:无法读取未定义的属性“推送”
这是我的代码:
function multiWords(words) {
class AWords {
constructor(words = []) {
this.words = words;
this.addWordFn = () => {};
}
setAddWordFn(fn) {
this.addWordFn = fn;
}
passWords() {
this.words.forEach(word => this.addWordFn(word));
}
}
class BWords {
constructor() {
this.bWords = [];
}
addWord(word) {
this.bWords.push(word);
}
}
let x = new AWords(words);
let y = new BWords();
x.setAddWordFn(y.addWord);
x.passWords();
return y.bWords;
}
console.log(multiWords(["one", "two", "three"]));
你有什么想法为什么会有不同的this
值? 非常感谢帕蒂
看来问题出现在这里:
this.words.forEach(word => this.addWordFn(word));
因为您在此处为addWordFn
设置的功能:
x.setAddWordFn(y.addWord);
需求的不同值this
比你与调用它。 您可以通过将 this 的正确值绑定到您的回调来修复它:
x.setAddWordFn(y.addWord.bind(y));
请记住,对于常规函数,函数内部的this
值取决于函数的调用方式。 当你调用一个函数obj.method()
则this
值内method()
将被设置为obj
。 因此,您使用错误的this
值调用addWord
是因为您已将其设置为某个其他对象的方法(该对象也没有所需的数据),并且正在从该对象调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.