javascript中带有super关键字的函数绑定



我想调用"超级";来自绑定函数。

这是我的用例:我有许多来自不同家长的儿童课程。我想将相同的函数绑定到所有这些函数(而不是复制粘贴它)。该函数需要调用;超级";相同函数的版本。

示例:

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

我想获得结果:

string1 
string2

我得到了这个结果(毫不奇怪,我会有一天):

"SyntaxError: 'super' keyword unexpected here".

我已经尝试将超级函数作为参数进行绑定。像这样:

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

结果(oriFunc恰好未定义):

TypeError: oriFunc is not a function

有什么解决方案吗?谢谢

您可以使用Object.getPrototypeOf两次而不是super:一次从实例导航到其内部原型(即Child.prototype),一次从该实例导航到内部原型(亦即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();

最新更新