【发布时间】:2018-08-18 09:47:20
【问题描述】:
在 Kyle Simpson 的 You-Don't-Know-Js 系列丛书中,同时在 this & Object Prototypes 一书中讨论了 es6 之前 javascript 中的类模式实现他在第 4 章中提到的系列,他称之为 pseudo-polymorphism。
他这样描述这种伪多态性:
但由于 JavaScript 的特殊性,显式伪多态性(因为阴影!)在需要此类(伪)多态引用的每个函数中创建脆弱的手动/显式链接。这会显着增加维护成本。此外,显式伪多态虽然可以模拟“多重继承”的行为,但只会增加复杂性和脆弱性。
据我在这里可以理解,这种伪多态性是一种不好的行为,我们最好避免这种行为,因为明确调用 SUPER 类,就像他关于调用 Vehicle 的示例中一样 Car 类内部的 em> 类,因此我们可以像这样显式调用:
function Car () {
Vehicle.call( this );
}
//also overriding Vehicle's methods
Car.prototype.methodName = function( p1 ) {
//manipulate p1 then call the super method.
Vehicle.prototype.methodName.call( this, p1 );
};
但我想知道这里的问题是否与 Vehicle 类名的显式使用有关,那么为什么我们不这样做:
function Car () {
this.super = Object.getPrototypeOf( this ).constructor;
this.super.call( this );
}
//also overriding Vehicle's methods
Car.prototype.methodName = function( p1 ) {
//manipulate p1 then call the super method.
this.super.prototype.methodName.call( this, p1 );
};
这不是在解决问题的其他面向类的语言中伪造或模仿 super 关键字吗?
【问题讨论】: