- 使用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])
私有方法
const _radius = Symbol()
const _draw = Symbol()
class Circle {
constructor(radius) {
this[_radius] = radius
}
[_draw]() {
console.log('draw')
}
}
const c = new Circle(1)
- 使用weakMap实现
私有变量
const _radius = new WeakMap()
class Circle {
constructor(radius) {
_radius.set(this, radius)
}
draw() {
console.log(_radius.get(this))
}
}
const c = new Circle(1)
私有方法
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)
箭头函数会将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)