2

In a library that I wish to extend without modifying its code, several classes inherit from the same imported one. That is in this BaseClass I would need to overwrite a specific method.

  • In the library (written in TypeScript) :
import { BaseClass } from './base_class';
export class ClassA extends BaseClass {}

import { BaseClass } from './base_class';
export class ClassB extends BaseClass {}
…
  • In the external extension I wish to write :
import { BaseClass } from 'library';
export class ExtendedBaseClass extends BaseClass {
    oneMethod() {
         const data = BaseClass.prototype.oneMethod.call(this);
         // make additional things with data
         return data;
    }
}

Is there a way for this new ExtendedBaseClass to become the parent of all ClassXs ? At least in a new extended and re-exported version of them without the need to copy their internal code.

4

2 回答 2

3

Is there a way for this new ExtendedBaseClass to become the parent of all ClassXs?

No.

An alternative might be to replace the one method directly on the base class:

import { BaseClass } from 'library';

const oneMethod = BaseClass.prototype.oneMethod;

Object.defineProperty(BaseClass.prototype, 'oneMethod', {
    value() {
         const data = oneMethod.call(this);
         // make additional things with data
         return data;
    },
});
于 2019-12-26T19:44:50.543 回答
1

There's no way to do exactly what you're asking, but you could achieve the same result by extending each class individually.

ExtendedClassA extends ClassA {
  oneMethod() {
    // call a shared method if you need to reuse
  }
}

// ExtendedClassB, etc
于 2019-12-26T19:45:55.243 回答