[英]Two classes one with reference to function to another different this value
I have problem and I don't know how to solve it:我有问题,我不知道如何解决:
this.bWords.push(word);
^
TypeError: Cannot read property 'push' of undefined类型错误:无法读取未定义的属性“推送”
here is my code:这是我的代码:
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"]));
Do you have any ideas why there is different this
value?你有什么想法为什么会有不同的
this
值? Many thanks Pati非常感谢帕蒂
It appears that the problem occurs here:看来问题出现在这里:
this.words.forEach(word => this.addWordFn(word));
because the function you've set for addWordFn
here:因为您在此处为
addWordFn
设置的功能:
x.setAddWordFn(y.addWord);
Needs a different value of this
than you are calling it with.需求的不同值
this
比你与调用它。 You can fix it by binding the right value of this to your callback:您可以通过将 this 的正确值绑定到您的回调来修复它:
x.setAddWordFn(y.addWord.bind(y));
Remember that for regular functions, the value of this
inside the function is determined by how the function is called.请记住,对于常规函数,函数内部的
this
值取决于函数的调用方式。 When you call a function with obj.method()
, the this
value inside of method()
will be set to obj
.当你调用一个函数
obj.method()
则this
值内method()
将被设置为obj
。 So, you're calling addWord
with the wrong this
value because you've made it a method of some other object (that does not also have the data it needs) and are calling it off that object.因此,您使用错误的
this
值调用addWord
是因为您已将其设置为某个其他对象的方法(该对象也没有所需的数据),并且正在从该对象调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.