ES6在类继承中使用原型进行访问

问题描述 投票:0回答:1

我正在尝试通过使用原型将大型的nodejs类文件分解为较小的文件。只要我不访问超类中的this变量,它就可以工作。

此代码具有两个类:ClassB扩展ClassA。在ClassB的构造函数中,我们传递一个变量,该变量将超类ClassA设置为this.page。然后,我们尝试从原型functionA。[]访问this.page

class ClassA  {
    constructor(page) {
        this.page = page
        console.log('[classA/constructor] has page', this.page)

    }

    /*
     *  Example A: This works!
     */
    // functionA = () => {
    //     console.log("has page", this.page)
    // }

    /*
     *  Example B: This works!
     */
    // functionA = function() {
    //     console.log("has page", this.page)
    // }

    /*
     *  Example C: This does not work!
     */
    // functionA() {
    //     console.log("has page", this.page)
    // }
}

/*
* Example D: This is what I really want to get working... does not work
*/
ClassA.prototype.functionA = function functionA() {
    console.log('[classA/functionA] has page', this.page)
}

class ClassB extends ClassA {
    constructor(page) {
        console.log('[classB/constructor] has page', page)
        super(page)
    }
}

ClassB.prototype.functionA = function () {
    console.log('[classB/functionA] has page', this.page)
    this.__proto__.functionA()
}

const classB = new ClassB('YES!');
classB.functionA();

取消注释并运行示例A和示例B可以正常工作,并提供以下正确的输出:

[classB/constructor] has page YES!
[classA/constructor] has page YES!
has page YES!

当切换到原型时(示例D,代码中未注释的一个),它断开,输出为:

[classB/constructor] has page YES!
[classA/constructor] has page YES!
[classB/functionA] has page YES!
[classB/functionA] has page undefined
[classA/functionA] has page undefined

我认为这与绑定有关,因为示例C也不起作用。但是我不明白为什么。

我正在尝试通过使用原型将大型的nodejs类文件分解为较小的文件。只要我不在超类中访问此变量,它就可以工作。此代码有两个类:ClassB扩展...

javascript node.js class ecmascript-6 prototype
1个回答
0
投票

调用this.__proto__.functionA()是问题。您正在调用functionA()时没有正确的对象。以这种方式进行调用会将this作为this.__proto__内部的this的值。显然这不是您想要的。

我不知道为什么首先使用functionA()而不是this.__proto__.functionA(),但是您可以使用this.functionA()强制使用正确的this

© www.soinside.com 2019 - 2024. All rights reserved.