天天看點

JSOOP 私有化屬性(Symbol和WeakMap)

  • 使用Symbol實作

私有屬性

const _radius = Symbol()
class Circle {
  constructor(radius) {
    this[_radius] = radius
  }
}
const c = new Circle(1)
const key = Object.getOwnPropertySymbols(c)[0]
console.log(c[key])
           
JSOOP 私有化屬性(Symbol和WeakMap)

 私有方法

const _radius = Symbol()
const _draw = Symbol()

class Circle {
  constructor(radius) {
    this[_radius] = radius
  }
  [_draw]() {
    console.log('draw')
  }
}
const c = new Circle(1)
           
JSOOP 私有化屬性(Symbol和WeakMap)
  •  使用weakMap實作

私有變量

const _radius = new WeakMap()

class Circle {
  constructor(radius) {
    _radius.set(this, radius)
  }
  draw() {
    console.log(_radius.get(this))
  }
}
const c = new Circle(1)
           
JSOOP 私有化屬性(Symbol和WeakMap)

私有方法

const _radius = new WeakMap()
const _move = new WeakMap()

class Circle {
  constructor(radius) {
    _radius.set(this, radius)
    _move.set(this, function() {
      console.log('move', this)
    })
  }
  draw() {
    _move.get(this)()
    console.log('draw')
  }
}
const c = new Circle(1)
           
JSOOP 私有化屬性(Symbol和WeakMap)
 箭頭函數會将this設定為包含他的函數,實作在私有方法中調用執行個體的所有成員
const _radius = new WeakMap()
const _move = new WeakMap()

class Circle {
  constructor(radius) {
    _radius.set(this, radius)
    _move.set(this, () => {
      console.log('move', this)
    })
  }
  draw() {
    _move.get(this)()
    console.log('draw')
  }
}
const c = new Circle(1)
           
JSOOP 私有化屬性(Symbol和WeakMap)

繼續閱讀