ES6 类 继承解决冲突的方法名
ES6 classes inheritance resolving conflicting method names
我希望 base
的 this.method2()
调用在实际执行 derived.method2()
时执行 base.method2()
(我了解行为背后的想法),是否可以实现没有方法重命名这里的最佳实践是什么?
const base = class {
method() {
this.method2();
}
method2() {
console.error("base.method2");
}
}
const derived = new class extends base {
method() {
super.method();
}
method2() {
console.error("derived.method2");
}
}
derived.method(); // want 'base.method2' here
您可以使用 call
来做到这一点。
method() {
base.prototype.method2.call(this);
}
在这种情况下,从技术上讲,您 不需要 使用 call
并提供 this
值,因为您不使用它,但是这是创建所需呼叫的最佳方式,因此它适用于所有情况。
顺便说一下,我不明白你想用 const base = class {}
语句实现什么。 class 声明不会那么令人惊讶:class base {}
.
我希望 base
的 this.method2()
调用在实际执行 derived.method2()
时执行 base.method2()
(我了解行为背后的想法),是否可以实现没有方法重命名这里的最佳实践是什么?
const base = class {
method() {
this.method2();
}
method2() {
console.error("base.method2");
}
}
const derived = new class extends base {
method() {
super.method();
}
method2() {
console.error("derived.method2");
}
}
derived.method(); // want 'base.method2' here
您可以使用 call
来做到这一点。
method() {
base.prototype.method2.call(this);
}
在这种情况下,从技术上讲,您 不需要 使用 call
并提供 this
值,因为您不使用它,但是这是创建所需呼叫的最佳方式,因此它适用于所有情况。
顺便说一下,我不明白你想用 const base = class {}
语句实现什么。 class 声明不会那么令人惊讶:class base {}
.