javascript,多态 new Myclass()?

标签 javascript class ecmascript-6

我有许多具有以下形式的类。

static defaultInstance() {

 if (!defaultInstance) {
   defaultInstance = new Child1()
 }
 return defaultInstance
}

由于它们有一个共同的基类,我想将共同的功能添加到基类中,但不知道如何。
(使用 new Child1() 时遇到问题)

最佳答案

如果 Child1 应该引用“当前”类,即调用 defaultInstance 的类,那么您可以这样做

defaultInstance = new this();

这遵循正常的 JavaScript 规则:如果您使用 Child1.defaultInstance() 调用该函数,则 this 引用 Child1

但是,这可能不会达到您想要的效果。如果您在基类上定义 defaultInstance,则所有子类共享相同 defaultInstance 变量。

如果您希望每个类都有一个实例,那么每个类都需要有自己的 defaultInstance 方法,或者您需要使用属性,例如

if (!this.__defaultInstance) {
  this.__defaultInstance = new this();
}

关于javascript,多态 new Myclass()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40275519/

相关文章:

c# - 是还是不是?我可以在不同的程序集中划分接口(interface)和实现类吗?

python - 如何打印一个可以包含自身的类

gulp - babel/6to5 - 导出模块时重复的代码

javascript - 将每个字符显示为数组的 Map 函数

python - 该类的两个不同实例在内存中具有相同的列表地址

javascript - 如何为 Angular 2 设置 gulp-typescript?

javascript - 在 ES6 中编写映射/集合的更简单方法(编译器或语法糖?)

javascript - 序列化多个重复项的数组

php - 从灯箱链接到不同尺寸的灯箱

javascript - CheckBoxList 检查单击时的所有项目仅工作一次