javascript - Function-binding with super keyword in javascript
问题描述
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
解决方案
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();
推荐阅读
- c# - 从 powerpoint 形状中读取 CustomerData
- jenkins - 当为该 gerrit 运行构建时,Gerrit 触发器不起作用
- spring-boot - OpenCSV:按照它在 csv 中出现的顺序获取标题名称列表
- laravel - 当您的服务器上的图像加载到 laravel 时,如何获得通知?在别的地方吗?
- html - 角crud向数据库添加功能
- spring - 尽管 application.properties 说 postgress,但 Spring 想要连接到 Mysql
- javascript - 我在 javascript 过滤中遇到问题,我没有在浏览器中获得过滤的项目,但是当我控制台过滤的产品时它工作得很好?
- python - 在此示例中,如何用字典中的相应值替换列表项?使用蟒蛇
- windows - 有没有办法转换 LocalProfileLoadTimeHigh 和 LocalProfileLoadTimeLow 注册表值?
- javascript - 将 Javascript 对象转换为 Date 对象