1

I would like to call "super" from a bound function.

Here is my use case: I have many child classes from different parents. I'd like to bind the same function to all of them (instead of copy pasting it). That function needs to call the "super" version of that same function.

Example:

class Parent {
    func() {
        console.log("string1");
    }
}

function boundFunc() {
    super.func();
    console.log(this.string2);
}

class Child extends Parent {
    constructor() {
        super();
        this.string2 = "string2"
        this.func = boundFunc.bind(this);
    }
}

const child = new Child();
child.func();

I would like to obtain result:

string1 
string2

I get this result instead (unsurprisingly, I'd day):

"SyntaxError: 'super' keyword unexpected here".

I've tried to pass the super function as an argument to bind. Like this:

function bindedFunc(thisArg, oriFunc) {
    oriFunc();
    console.log(this.string2);
}

class Child extends Parent {
    constructor() {
        super();
        this.string2 = "string2"
        this.func = bindedFunc.bind(this, super.func);
    }
}

Result (oriFunc happens to be undefined):

TypeError: oriFunc is not a function

Any solution? Thank you

FourchetteVerte
  • 333
  • 3
  • 7
  • It's important to understand that the `class` mechanism is *mostly* a parse-time "sugar" feature that builds object structures on top of older basic mechanisms. Using `super` inside what is (as far as the parser is concerned) a stand-alone function doesn't make sense. – Pointy Mar 11 '21 at 04:01

1 Answers1

3

Instead of super, you can use Object.getPrototypeOf twice: once to navigate from the instance to its internal prototype (which is Child.prototype), and once to navigate from that to its internal prototype (which is Parent.prototype):

class Parent {
    func() {
        console.log("string1");
    }
}

function boundFunc() {
    Object.getPrototypeOf(Object.getPrototypeOf(this)).func();
    console.log(this.string2);
}

class Child extends Parent {
    constructor() {
        super();
        this.string2 = "string2"
        this.func = boundFunc.bind(this);
    }
}

const child = new Child();
child.func();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thank you! However I found out this is not exactly the equivalent of super. This won't be able to access any attribute from Parent. This would: Object.getPrototypeOf(Object.getPrototypeOf(this)).func.call(this);. This would also work: Parent.prototype.func.call(this);. Last one is less generic, but it might be prettier, depending on use case of future reader :) – FourchetteVerte Mar 11 '21 at 16:58