【问题标题】:Javascript: Class Design Pattern - pseudo-polymorphismJavascript:类设计模式 - 伪多态
【发布时间】: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 关键字吗?

【问题讨论】:

    标签: javascript polymorphism


    【解决方案1】:

    ...为什么我们不这样做...

    因为它不起作用,但你距离第一个掉入陷阱的人。 :-) 尝试添加CarLuxuryCar 子类以查看问题:现在this.super(即使在Car 代码中)指的是Car,而不是Vehicle

    有些模式可以避免在 ES5 级代码中的 Car 中显式使用名称 Vehicle(我是 wrote one of them up in 2009),但它们现在已经过时了;相反,我们使用 ES2015 中的 class 语法(必要时进行转译):

    class Vehicle {
        methodName() {
            console.log("Vehicle#methodName");
        }
    }
    class Car extends Vehicle {
        methodName() {
            super.methodName();
            console.log("Car#methodName");
        }
    }
    class LuxuryCar extends Car {
        methodName() {
            super.methodName();
            console.log("LuxuryCar#methodName");
        }
    }
    
    const l = new LuxuryCar();
    l.methodName();

    【讨论】:

    • 是的,谢谢,我没有考虑过这个子类点,但现在它清楚了:)
    • 对,[[HomeObject]] 在 ES6 之前并不存在,它实际上启用了super ...
    猜你喜欢
    • 1970-01-01
    • 2011-09-03
    • 1970-01-01
    • 2013-08-27
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多