javascript - 在 ES6 类方法中,如何确保“this”始终指向类本身,而不是子类?
问题描述
例如:
class Parent {
func1() {
console.log("I am func1, in class Parent");
}
func2() {
this.func1();
}
}
class Child extends Parent {
func1() {
console.log("I am func1, in class Child");
}
}
let a = new Child();
a.func2();
因为“this”在调用a.func2()时指向Child,所以会输出“I am func1, in class Child”。
但是现在我希望 Parent.func2() 在任何情况下始终调用 Parent.func1(),即使“this”与 Child 绑定,我该怎么做?
我试过了
func2() {
super.func1();
}
显然当 Parent 调用 func2() 时它不能工作:
let b = new Parent();
b.func2(); //not work
我想要这样的东西:
class Parent {
func1() {
console.log("I am func1, in class Parent");
}
func2() {
Parent.func1(); //always access Parent.func1() even if func1() is overrode.
}
}
请帮忙。
解决方案
没有特殊的语法,您需要明确引用您要准确调用的方法:
class Parent {
func1() {
console.log("I am func1, in class Parent");
}
func2() {
Parent.prototype.func1.call(this);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
}
推荐阅读
- ruby-on-rails - 如何将我的主页与其他页面连接起来?
- reactjs - 如何使用谷歌材料 UI 为菜单项编写测试用例
- jolt - 按条件进行 JOLT 变换
- assembly - 在 8086 中添加两个 8 位数字给出错误答案
- jsf - PrimeFaces commandButton 在提交后不起作用
- python - Python 装饰器将实例初始化变量转换为自身属性
- windows-subsystem-for-linux - 为什么“systemctl”不能在 Windows 上的 Ubuntu 终端中工作?
- java - if 语句中的多个条件 - first 始终为真
- php - 使用 Guzzle 上传带有文件的数据 - Laravel
- reactjs - 为反应库配置汇总