詳解ES6實現(xiàn)類的私有變量的幾種寫法
閉包實現(xiàn)類的私有變量方式
私有變量不共享
通過 new 關(guān)鍵字 person 的構(gòu)造函數(shù)內(nèi)部的 this 將會指向 Tom,開辟新空間,再次全部執(zhí)行一遍,
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
私有變量可共享
為避免每個實力都生成了一個新的私有變量,造成是有變量不可共享的問題,我們可以將這個私有變量放在類的構(gòu)造函數(shù)到外面,繼續(xù)通過閉包來返回這個變量。
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
那這樣的話,如果兩種方法混合使用,那就可以擁有可共享和不可共享的兩種私有變量。
缺點:實例化時會增加很多副本,比較耗內(nèi)存。
Symbol實現(xiàn)類的私有變量方式
symbol 簡介:
創(chuàng)建一個獨一無二的值,所有 Symbol 兩兩都不相等,創(chuàng)建時可以為其添加描述Symble("desc"),目前對象的健也支持 Symbol 了。
const name = Symbol('名字')
const person = { // 類名
[name]:'www',
say(){
console.log(`name is ${this[name]} `)
}
}
person.say()
console.log(name)
使用Symbol為對象創(chuàng)建的健無法迭代和Json序列化,所以其最主要的作用就是為對象添加一個獨一無二的值。
但可以使用getOwnProporitySymbols()獲取Symbol.
缺點:新語法瀏覽器兼容不是很廣泛。
symbol 實現(xiàn)類的私有變量
推薦使用閉包的方式創(chuàng)建 Symbol 的的引用,這樣就可以在類的方法區(qū)獲得此引用,避免方法都寫在構(gòu)造函數(shù),每次創(chuàng)建新實例都要重新開辟空間賦值方法,造成內(nèi)存浪費。
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 簡介

實現(xiàn):
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 的方式來實現(xiàn)類似私有變量省內(nèi)存,易回收,又能夠被更多的瀏覽器兼容,也是最推薦的實現(xiàn)方法。
到此這篇關(guān)于詳解ES6實現(xiàn)類的私有變量的幾種寫法的文章就介紹到這了,更多相關(guān)ES6 類的私有變量內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JavaScript仿小米官網(wǎng)注冊登錄功能的實現(xiàn)
這篇文章主要為大家詳細(xì)介紹了如何通過JavaScript實現(xiàn)仿小米官網(wǎng)登錄注冊完整功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-11-11
中級前端工程師必須要掌握的27個JavaScript 技巧(干貨總結(jié))
這篇文章主要介紹了中級前端工程師必須要掌握的27個JavaScript 技巧(干貨總結(jié)),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-09-09

