动态扩展ES6类

时间:2019-06-06 19:17:27

标签: javascript dynamic ecmascript-6 extends es6-class

如何在js es6中轻松实现一种混合或扩展动态多类继承?

//这里的示例有3个类,但是它们需要从上下文扩展。

class Type1 { constructor() {} };
class Type2 { constructor() {} };
class Type3 { constructor() {} };

//,这里我有其他类继承,但不需要上下文。

/** return dynamically a class*/
function dynamically_Extends(extendsType) {
    switch (extendsType) {
        case 'type1': return Type1 ;break;
        case 'type2': return Type2 ;break;
        case 'type3': return Type3 ;break;
        default: console.error('class not exist') ;break;
    };
};

class AA {
    constructor(type) {
        //not work: example of extend during constructor?
        extends dynamically_Extends(type); 
        super()
    };
};

class A extends AA{
    constructor(type) {
        super(type)
    };
};

创建对象时,我希望它具有类似的内容

const obj1 = new A('type1'); // class heritance: A=>AA=>type1
const obj2 = new A('type2'); // class heritance: A=>AA=>type2
const obj3 = new A('type3'); // class heritance: A=>AA=>type3

我想第二次延长A,但要根据情况动态调整。 在构造函数期间或之后执行此操作的任何提示或简便方法? 我想保留所有东西的糖类代码。

1 个答案:

答案 0 :(得分:0)

除了提供的所有其他好处类之外,它们还承诺提供一定的API。动态扩展将使兑现这些承诺相对容易得多。 (尽管在JS中没有动态扩展也很容易做到)。例如。 obj1是否支持Type1.prototype.method1Type2.prototype.method2

可以考虑采用另一种更传统的方法(从而更易于维护和阅读)来重新组织您的类层次结构。类Type1Type2Type3可以从class A继承。