从父类调用子方法是好是坏?
class Parent {
constructor() {
// if 'autoPlay' exists (was implemented) in chain
if (this.autoPlay) {
this.autoPlay(); // execute from parent
}
}
}
class ChildA extends Parent {
autoPlay() {
console.log('Child');
}
}
class ChildB extends Parent {
// 'autoPlay' wasn't implemented
}
const childA = new ChildA();
const childB = new ChildB();
最佳答案
Is it a good practice to call a child method from a parent class?
是的,这是一种完全正常的做法。父类只是调用实例的一些方法,如果子类重写了该方法,则调用子方法。但是,您通常不会执行这样的“我的实例是否定义了此方法”测试,您只是调用它。如果您默认什么都不做,只需定义一个空方法(如@scipper 的回答)。如果您想使该方法抽象化(强制子类覆盖它),您可以将其保留为未定义状态或定义一个抛出适当异常的方法。
Is is a bad practice to call a child method from a parent constructor?
Yes. Don't do that. (这是所有语言的问题)。
构造函数的目的是初始化实例,没有别的。将副作用的调用留给调用者。这将确保所有子构造函数也将完成它们的初始化。
一个人为的例子:
class Parent {
autoPlay() {
this.play("automatically "); // call child method
}
play(x) {
console.log(x+"playing default from "+this.constructor.name);
}
}
class ChildA extends Parent {
// does not override play
}
class ChildB extends Parent {
constructor(song) {
super();
this.song = song;
}
play(x) {
console.log(x+"playing "+this.song+" from ChildB");
}
}
const child1 = new ChildA();
child1.autoPlay();
const child2 = new ChildB("'Yeah'");
child2.autoPlay();
请注意,如果 Parent
构造函数确实调用了 autoplay
,那将如何不起作用。如果您不想在实例化后到处都需要额外的方法调用,请使用辅助函数。它甚至可能是一个静态方法:
class Parent {
autoPlay() { … }
play { … }
static createAndAutoPlay(...args) {
const instance = new this(...args);
instance.autoPlay();
return instance;
}
}
…
const child1 = ChildA.createAndAutoPlay();
const child2 = ChildB.createAndAutoPlay("'Yeah'");
关于javascript - 在 ES6 中从父类调用子方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47820030/