欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解ES6實(shí)現(xiàn)類的私有變量的幾種寫法

 更新時(shí)間:2021年02月10日 09:26:45   作者:Do_Better  
這篇文章主要介紹了詳解ES6實(shí)現(xiàn)類的私有變量的幾種寫法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

閉包實(shí)現(xiàn)類的私有變量方式

私有變量不共享

通過 new 關(guān)鍵字 person 的構(gòu)造函數(shù)內(nèi)部的 this 將會(huì)指向 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è)實(shí)力都生成了一個(gè)新的私有變量,造成是有變量不可共享的問題,我們可以將這個(gè)私有變量放在類的構(gòu)造函數(shù)到外面,繼續(xù)通過閉包來返回這個(gè)變量。

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í)例化時(shí)會(huì)增加很多副本,比較耗內(nèi)存。

Symbol實(shí)現(xiàn)類的私有變量方式

symbol 簡介:

創(chuàng)建一個(gè)獨(dú)一無二的值,所有 Symbol 兩兩都不相等,創(chuàng)建時(shí)可以為其添加描述Symble("desc"),目前對(duì)象的健也支持 Symbol 了。

const name = Symbol('名字')
const person = { // 類名
  [name]:'www',
  say(){
    console.log(`name is ${this[name]} `) 
  } 
} 
person.say()
console.log(name)

使用Symbol為對(duì)象創(chuàng)建的健無法迭代和Json序列化,所以其最主要的作用就是為對(duì)象添加一個(gè)獨(dú)一無二的值。
但可以使用getOwnProporitySymbols()獲取Symbol.
缺點(diǎn):新語法瀏覽器兼容不是很廣泛。

symbol 實(shí)現(xiàn)類的私有變量

推薦使用閉包的方式創(chuàng)建 Symbol 的的引用,這樣就可以在類的方法區(qū)獲得此引用,避免方法都寫在構(gòu)造函數(shù),每次創(chuàng)建新實(shí)例都要重新開辟空間賦值方法,造成內(nèi)存浪費(fè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 簡介

實(shí)現(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 的方式來實(shí)現(xiàn)類似私有變量省內(nèi)存,易回收,又能夠被更多的瀏覽器兼容,也是最推薦的實(shí)現(xiàn)方法。

到此這篇關(guān)于詳解ES6實(shí)現(xiàn)類的私有變量的幾種寫法的文章就介紹到這了,更多相關(guān)ES6 類的私有變量內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論