skip to Main Content
class bcomp {
 some(){
    console.log("bcomp");
 }
}
class acomp extends bcomp {
 some(){
    super.some();
    console.log("acomp");
 }
}
var ins = new acomp();
ins.some()

so output will be

bcomp
acomp

I need to override some method of acomp with super keyword

acomp.prototype.some = function (params) {
    super.some();
    console.log("new acomp");
}
SyntaxError: 'super' keyword unexpected here

How to achieve the above?

3

Answers


  1. Call the some method of the parent class directly like this

    bcomp.prototype.some.call(this);
    

    instead of super.some()

    Login or Signup to reply.
  2. A generic patch approach for some which targets an objects 2nd prototype within this objects prototype chain without having to know the object’s/instance’s involved classes would make use of Object.getPrototypeOf twice.

    In addition one should make use of Reflect.getOwnPropertyDescriptor together with Reflect.defineProperty in order to patch this new some method in its most correct way.

    function root(value) {
      return Object.getPrototypeOf(value);
    }
    
    // new prototypal `AComp` method.
    function some() {
    
      // // `BComp.prototype`
      // root(
      // 
      //   // `AComp.prototype`
      //   root(this)
      // )
      // ?.some();
    
      // root(root(this))?.some();
    
      root(root(this))?.some.call(this);
    
      console.log("new acomp");
    }
    
    Reflect.defineProperty(
      AComp.prototype, 'some', {
        ...Reflect.getOwnPropertyDescriptor(AComp.prototype, 'some'),
        value: some,
      },
    );
    
    (new AComp).some();
    .as-console-wrapper { min-height: 100%!important; top: 0; }
    <script>
    class BComp {
     some(){
        console.log("bcomp");
     }
    }
    class AComp extends BComp {
     some(){
        super.some();
        console.log("acomp");
     }
    }
    </script>
    Login or Signup to reply.
  3. JS is a prototypical language but at the same time it is a functional language. It’s best not to modify the prototype methods once they are set. As i remember they are costly operations. Instead it’s a reasonable approach to make the some function to accept the desired functionality.

    class bcomp {
     some(){
        console.log("bcomp");
     }
    }
    class acomp extends bcomp {
     #f;
     some(f = this.#f || (_ => console.log("acomp"))) {
        this.#f = f;
        super.some()
        this.#f();
     }
    }
    var ins = new acomp();
    ins.some();                              // uses defaut action
    ins.some(_ => console.log("new acomp")); // sets #f and makes it the new default action.
    ins.some()                               // uses the new default action
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search