问题描述
这是我的用例:我有很多来自不同父母的子类。我想将相同的功能绑定到所有这些(而不是复制粘贴)。该函数需要调用同一函数的“超级”版本。
示例:
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".
我尝试将 super 函数作为参数传递给绑定。像这样:
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
有什么解决办法吗?谢谢
解决方法
代替 super
,您可以使用 Object.getPrototypeOf
两次:一次从实例导航到其内部原型(即 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();