【发布时间】:2021-06-09 01:47:12
【问题描述】:
我想从绑定函数中调用“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
有什么解决办法吗?谢谢
【问题讨论】:
-
了解
class机制主要是一种在旧的基本机制之上构建对象结构的解析时“糖”功能,这一点很重要。在独立函数中使用super(就解析器而言)没有意义。
标签: javascript super function-binding