两个类一个引用函数到另一个不同的this值
Two classes one with reference to function to another different this value
我有问题,不知道如何解决:
this.bWords.push(word);
^
TypeError: 无法读取未定义的 属性 'push'
这是我的代码:
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()
调用函数时,method()
中的 this
值将设置为 obj
。因此,您使用错误的 this
值调用 addWord
因为您已将其作为其他某个对象的方法(该对象也没有所需的数据)并且正在从该对象调用它.
我有问题,不知道如何解决:
this.bWords.push(word);
^
TypeError: 无法读取未定义的 属性 'push'
这是我的代码:
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()
调用函数时,method()
中的 this
值将设置为 obj
。因此,您使用错误的 this
值调用 addWord
因为您已将其作为其他某个对象的方法(该对象也没有所需的数据)并且正在从该对象调用它.