代码之家  ›  专栏  ›  技术社区  ›  A. L

如何创建一个基于两个独立基类的公共子类

  •  0
  • A. L  · 技术社区  · 4 年前

    我现在有两个类,每个类都有一个子类,但这些子类实际上具有相同的扩展函数。我想知道是否有一种方法可以通过更松散的类来防止代码重复。

    我需要扩展父类的原因是,我希望能够在子类中访问父类的方法。

    代码如下。

    class Base1 {
        /**
         * @param {() => cy} getWrapper
         */
        constructor( getWrapper ) {
            this._getWrapper = getWrapper;
        }
    
        getSomething () {
            return this.getWrapper().find('something');
        }
        getWrapper () {
            return this._getWrapper();
        }
    }
    class Base2 {
        /**
         * @param {() => cy} getWrapper
         */
        constructor( getWrapper ) {
            this._getWrapper = getWrapper;
        }
    
        getHeading () {
            return this.getWrapper().find('heading');
        }
        getWrapper () {
            return this._getWrapper();
        }
    }
    
    class ReWrapBase1 extends Base1 {
        eq ( index ) {
            return new Base1( () => this.getWrapper().eq( index ) );
        }
        getWrapper () {
            return this._getWrapper().find( '[class*=SummaryItemstyles__Wrapper]' );
        }
    }
    class ReWrapBase2 extends Base2 {
        eq ( index ) {
            return new Base2( () => this.getWrapper().eq( index ) );
        }
        getWrapper () {
            return this._getWrapper().find( '[class*=SummaryItemstyles__Wrapper]' );
        }
    }
    

    我最初的想法是让构造函数持有类,但后来我意识到我实际上无法使用父类的方法,这违背了目的。

    class ReWrapAny {
        constructor(returnedClass) {
            this._returnedClass = returnedClass
        }
        eq ( index ) {
            return new this._returnedClass( () => this.getWrapper().eq( index ) );
        }
        getWrapper () {
            return this._getWrapper().find( '[class*=SummaryItemstyles__Wrapper]' );
        }
    }
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   A. L    4 年前

    将其更改为使用混入。

    function createMixin (baseClass) {
        eq ( index ) {
            return new baseClass( () => this.getWrapper().eq( index ) );
        }
        getWrapper () {
            return this._getWrapper().find( '[class*=SummaryItemstyles__Wrapper]' );
        }
    }
    export class ExportBase extends Base1 {}
    Object.assign(AmountCards.prototype, createClass(Base1))