首页 > 解决方案 > 这是在扩展类中未定义的

问题描述

我有这 3 个文件:

bar.js

class Bar {
    test(p) {
        console.log(p);
    }
}

module.exports = Bar;

baz.js

const Bar = require('./bar');

class Baz extends Bar {
    test2(p) {
        this.test(p);
    }
}

module.exports = Baz;

foo.js

const Baz = require('./baz');
const { test2 } = new Baz();

test2('test');

当我传递'test'给 时new Baz.test2(),我希望它将它传递给this.test(p)它应该记录的超类 () 'test'。但是,它抛出了错误:

        this.test(p);
             ^

TypeError: Cannot read property 'test' of undefined

我究竟做错了什么?为什么是this未定义的,我认为它应该引用类本身?

标签: node.jsecmascript-6

解决方案


test2与原始上下文(实例)分开使用Bar,应绑定到正确的this.

如果预期它是设计上的回调,则无法从名称中说出来。如果是,它可以在构造函数中绑定:

class Bar {
    constructor () {
        this.test = this.test.bind(this);
    }
    ...
}

否则它可以就地绑定:

const test2 = new Baz().test2.bind(this);

test2('test');

或者只是不与上下文分开使用:

const baz = new Baz()

baz.test2('test');

推荐阅读