简体   繁体   English

动态扩展ES6类

[英]Extends ES6 class dynamically

how perform easily a kind of mixing or extends dynamic multiple class inheritance in js es6 ? 如何在js es6中轻松实现一种混合或扩展动态多类继承?

// example here i have 3 class but they will need to be extends from context. //示例这里我有3个类,但它们需要从上下文扩展。

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

// and here i have other class inheritance but not need context. //这里我有其他类继承但不需要上下文。

/** 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)
    };
};

what i want it have something like this when i create objects 当我创建对象时,我想要它有这样的东西

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

i want extends A 2nd time but with a dynamic context according to conditions. 我想延伸A第二时间但具有根据条件的动态上下文。 Any tips or easy way to perform this during constructor or after ? 在构造函数期间或之后执行此操作的任何提示或简单方法? I want keep class sugar code for all thing. 我想保留所有的糖类代码。

In addition to all the other benefits classes provide, they also promise a certain API. 除了所提供的所有其他好处之外,他们还承诺使用某种API。 Dynamic extension would make it relatively much easier to break such promises. 动态扩展会使打破这种承诺变得相对容易。 (though it's pretty easy to do so without dynamic extensions anyways in JS). (尽管在JS中没有动态扩展这样做很容易)。 Eg does obj1 support Type1.prototype.method1 ? 例如, obj1支持Type1.prototype.method1 Type2.prototype.method2 ? Type2.prototype.method2

An alternative and more traditional (thereby easier to maintain and read) approach to consider, could be to reorganize you class hierarchy. 另一种更传统(因此更易于维护和阅读)的方法可以用来重新组织您的类层次结构。 Class Type1 , Type2 , and Type3 could inherit from class A . Type1Type2Type3可以从class A继承。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM