Javascript无法读取未定义的属性“x”

我不明白下面代码中的错误。我尝试从另一个类调用另一个类的函数。但我给出了错误error: Uncaught TypeError: Cannot read property '_name' of undefined

class Person {
    constructor() {
        this._name = "Name-Person";
    }

    getName() {
        return this._name;
    }
}

class Test1 {
    constructor() {
        let p = new Person();
        new Test2(p.getName);
    }
}

class Test2 {
    constructor(getName) {
        console.log(getName());
    }
}

new Test1()

回答

将函数传递给Test2您时需要绑定p到该函数

new Test2(p.getName.bind(p));
new Test2(p.getName.bind(p));


以上是Javascript无法读取未定义的属性“x”的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>