javascript – 从ES6中的父类调用子方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 从ES6中的父类调用子方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1809字,纯文字阅读大概需要3分钟。
内容图文
![javascript – 从ES6中的父类调用子方法](/upload/InfoBanner/zyjiaocheng/698/f383d1a8037f4efb8c68ceb118547b8a.jpg)
从父类调用子方法是好/坏的做法?
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 = this;
}
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中的父类调用子方法全部内容,希望文章能够帮你解决javascript – 从ES6中的父类调用子方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。