ES6中实现单例模式
1、通过构造函数
class SingletonApple {
constructor(name, creator) {
//首次使用构造器实例
if (!SingletonApple.instance) {
this.name = name;
this.creator = creator;
//将this挂载到SingletonApple这个类的instance属性上
SingletonApple.instance = this;
}
return SingletonApple.instance;
}
}
2、通过静态方法
class SingletonApple {
constructor(name, creator) {
this.name = name;
this.creator = creator;
}
//静态方法
static getInstance(name, creator) {
if(!this.instance) {
this.instance = new SingletonApple(name, creator);
}
return this.instance;
}
}
最后
以上就是糊涂电话最近收集整理的关于ES6中实现单例模式的全部内容,更多相关ES6中实现单例模式内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复