閉包實現類的私有變量方式
私有變量不共享
通過 new 關鍵字 person 的構造函數內部的 this 將會指向 Tom,開辟新空間,再次全部執行一遍,
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 |
私有變量可共享
為避免每個實力都生成了一個新的私有變量,造成是有變量不可共享的問題,我們可以將這個私有變量放在類的構造函數到外面,繼續通過閉包來返回這個變量。
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 |
那這樣的話,如果兩種方法混合使用,那就可以擁有可共享和不可共享的兩種私有變量。
缺點:實例化時會增加很多副本,比較耗內存。
Symbol實現類的私有變量方式
symbol 簡介:
創建一個獨一無二的值,所有 Symbol 兩兩都不相等,創建時可以為其添加描述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為對象創建的健無法迭代和Json序列化,所以其最主要的作用就是為對象添加一個獨一無二的值。
但可以使用getOwnProporitySymbols()獲取Symbol.
缺點:新語法瀏覽器兼容不是很廣泛。
symbol 實現類的私有變量
推薦使用閉包的方式創建 Symbol 的的引用,這樣就可以在類的方法區獲得此引用,避免方法都寫在構造函數,每次創建新實例都要重新開辟空間賦值方法,造成內存浪費。
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 創建私有變量
MDN 簡介
實現:
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()) |
總結
綜上 weakmap 的方式來實現類似私有變量省內存,易回收,又能夠被更多的瀏覽器兼容,也是最推薦的實現方法。
到此這篇關于詳解ES6實現類的私有變量的幾種寫法的文章就介紹到這了,更多相關ES6 類的私有變量內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://juejin.cn/post/6926866949162926094