閉包實(shí)現(xiàn)類的私有變量方式
私有變量不共享
通過 new 關(guān)鍵字 person 的構(gòu)造函數(shù)內(nèi)部的 this 將會指向 Tom,開辟新空間,再次全部執(zhí)行一遍,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
class Person{ constructor(name){ let _num = 100; this .name = name; this .getNum = function (){ return _num; } this .addNum = function (){ return ++_num } } } const tom = new Person( 'tom' ) const jack = new Person( 'jack' ) tom.addNum() console.log(tom.getNum()) //101 console.log(jack.getNum()) //100 |
私有變量可共享
為避免每個實(shí)力都生成了一個新的私有變量,造成是有變量不可共享的問題,我們可以將這個私有變量放在類的構(gòu)造函數(shù)到外面,繼續(xù)通過閉包來返回這個變量。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
const Person = ( function () { let _num = 100; return class _Person { constructor(name) { this .name = name; } addNum() { return ++_num } getNum() { return _num } } })() const tom = new Person( 'tom' ) const jack = new Person( 'jack' ) tom.addNum() console.log(tom.getNum()) //101 console.log(jack.getNum()) //101 |
那這樣的話,如果兩種方法混合使用,那就可以擁有可共享和不可共享的兩種私有變量。
缺點(diǎn):實(shí)例化時會增加很多副本,比較耗內(nèi)存。
Symbol實(shí)現(xiàn)類的私有變量方式
symbol 簡介:
創(chuàng)建一個獨(dú)一無二的值,所有 Symbol 兩兩都不相等,創(chuàng)建時可以為其添加描述Symble("desc"),目前對象的健也支持 Symbol 了。
1
2
3
4
5
6
7
8
9
|
const name = Symbol( '名字' ) const person = { // 類名 [name]: 'www' , say(){ console.log(`name is ${ this [name]} `) } } person.say() console.log(name) |
使用Symbol為對象創(chuàng)建的健無法迭代和Json序列化,所以其最主要的作用就是為對象添加一個獨(dú)一無二的值。
但可以使用getOwnProporitySymbols()獲取Symbol.
缺點(diǎn):新語法瀏覽器兼容不是很廣泛。
symbol 實(shí)現(xiàn)類的私有變量
推薦使用閉包的方式創(chuàng)建 Symbol 的的引用,這樣就可以在類的方法區(qū)獲得此引用,避免方法都寫在構(gòu)造函數(shù),每次創(chuàng)建新實(shí)例都要重新開辟空間賦值方法,造成內(nèi)存浪費(fèi)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
const Person = ( function () { let _num = Symbol( '_num:私有變量' ); return class _Person { constructor(name) { this .name = name; this [_num] = 100 } addNum() { return ++ this [_num] } getNum() { return this [_num] } } })() const tom = new Person( 'tom' ) const jack = new Person( 'jack' ) console.log(tom.addNum()) //101 console.log(jack.getNum()) //100 |
通過 weakmap 創(chuàng)建私有變量
MDN 簡介
實(shí)現(xiàn):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
const Parent = ( function () { const privates = new WeakMap(); return class Parent { constructor() { const me = { data: "Private data goes here" }; privates.set( this , me); } getP() { const me = privates.get( this ); return me } } })() let p = new Parent() console.log(p) console.log(p.getP()) |
總結(jié)
綜上 weakmap 的方式來實(shí)現(xiàn)類似私有變量省內(nèi)存,易回收,又能夠被更多的瀏覽器兼容,也是最推薦的實(shí)現(xiàn)方法。
到此這篇關(guān)于詳解ES6實(shí)現(xiàn)類的私有變量的幾種寫法的文章就介紹到這了,更多相關(guān)ES6 類的私有變量內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://juejin.cn/post/6926866949162926094