- 使用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)


本文探讨了如何在JavaScript中实现私有属性和方法,包括使用Symbol创建私有属性和私有方法,以及利用WeakMap来实现私有变量和私有方法。还特别提到了箭头函数在实现私有方法中如何保持正确的this指向,以便访问实例的所有成员。
775

被折叠的 条评论
为什么被折叠?



