我现在有两个类,每个类都有一个子类,但这些子类实际上具有相同的扩展函数。我想知道是否有一种方法可以通过更松散的类来防止代码重复。
我需要扩展父类的原因是,我希望能够在子类中访问父类的方法。
代码如下。
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]' );
}
}