我正在尝试通过使用原型将大型的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扩展...
调用this.__proto__.functionA()
是问题。您正在调用functionA()
时没有正确的对象。以这种方式进行调用会将this
作为this.__proto__
内部的this
的值。显然这不是您想要的。
我不知道为什么首先使用functionA()
而不是this.__proto__.functionA()
,但是您可以使用this.functionA()
强制使用正确的this
。