繁体   English   中英

两个类一个引用函数到另一个不同的 this 值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM