我是靠谱客的博主 稳重皮卡丘,这篇文章主要介绍es6实现单例模式 class类 静态方法,现在分享给大家,希望可以做个参考。

es6的 class类 又被叫做es5 构造函数的语法糖

先看看es5怎么用构造函数实现类:

复制代码
1
2
3
4
5
6
7
8
9
10
11
function Person(name, gender) { this.name = name this.gender = gender } Person.prototype.say = function() { console.log('I am the say function inside Person') } let person1 = new Person('Dean', 'male') console.log(person1.name) person1.say()

在这里插入图片描述

再看看es6怎么实现类:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
class Person { constructor(name, gender) { this.name = name this.gender = gender } say() { console.log('I am the say function inside class Person') } } let person1 = new Person('Jing', 'female') console.log(person1.name) person1.say()

在这里插入图片描述

我们再看一下这行代码:
在这里插入图片描述
在这里插入图片描述

说明es6 class类确实是es5构造函数的语法糖

接着我们看看es6如何实现单例模式

这里不得不引入一个概念,静态方法static

静态方法static通俗的说就是只有类自己可以调用的方法,类的实例对象是不能调用类的静态方法static

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class WarMachine { constructor(name, attackValue, type) { this.name = name this.attackValue = attackValue this.type = type } static getInstance(name, attackValue, type) { if (!this.instance) { this.instance = new WarMachine(name, attackValue, type) } return this.instance } } let wm1 = WarMachine.getInstance('TropperD', 100, 'aircraft') let wm2 = WarMachine.getInstance('StormBreaker', 199, 'submarine') console.log(61, wm1 === wm2) console.log('wm1', wm1) console.log('wm2', wm2) console.log(64, wm1 === wm2) console.log('----------') let wm3 = new WarMachine('oops..', 50, 'lolipop') console.log('wm3', wm3)

我们看一下执行结果:
在这里插入图片描述
wm1和wm2虽然在调用getInstance方法时候传入的参数不一样,但是它们两个却是指向同一个对象
当然如果继续使用new关键词创建实例的话,是可以创建不同的实例对象的

最后

以上就是稳重皮卡丘最近收集整理的关于es6实现单例模式 class类 静态方法的全部内容,更多相关es6实现单例模式内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部