我是靠谱客的博主 糊涂电话,这篇文章主要介绍ES6中实现单例模式,现在分享给大家,希望可以做个参考。

ES6中实现单例模式

1、通过构造函数
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
class SingletonApple { constructor(name, creator) { //首次使用构造器实例 if (!SingletonApple.instance) { this.name = name; this.creator = creator; //将this挂载到SingletonApple这个类的instance属性上 SingletonApple.instance = this; } return SingletonApple.instance; } }

2、通过静态方法

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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中实现单例模式内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(81)

评论列表共有 0 条评论

立即
投稿
返回
顶部