javascriptecmascript-6javascript-import

Hacking the import statement to extend an inherited class


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.

import { BaseClass } from './base_class';
export class ClassA extends BaseClass {}

import { BaseClass } from './base_class';
export class ClassB extends BaseClass {}
…
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.


Solution

  • 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;
        },
    });