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

4

1 回答 1

2

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();

于 2021-03-11T03:59:49.683 回答