- 使用约定, 默认以
_
开头 ```javascript // 优点 // 简单、调试方便、兼容性好
// 缺点 // 外部可访问,命名冲突, class Demo { constructor() { this._private = “private” } getPrivate() { return this._private; } } const demo = new Demo(); console.log(demo.getPrivate()); //private console.log(demo._private);
2. 使用闭包
```javascript
/**
实现1
优点,没有命令冲突,外部不能访问和修改
缺点,类构造器逻辑变复杂,方法存在类实例上,子类无法继承,增加性能开销
**/
class Demo {
constructor() {
this._private = "";
_private = "private";
this.getPrivate = function() {return _private};
}
}
const demo = new Demo();
console.log(demo.getPrivate()); //private
console.log(demo._private); // undefined
/**
实现2
优点:无命名冲突,外部无法访问和修改
缺点:写法叫复杂,增加性能开销
**/
const Demo = (function(){
var _private = '';
class Demo {
constructor() {
_private = 'private';
}
getPrivate() {
return _private;
}
}
return Demo;
})()
const demo = new Demo();
console.log(demo.getPrivate()); //private
console.log(demo._private); // undefined
- 使用Symbol
/**
优点,无命名冲突,外部无法访问和修改,无性能损失
缺点,写法负责,兼容性一般
**/
const Demo = (function(){
var _private = Symbol('private')
class Demo {
constructor() {
this[_private] = 'private';
}
getPrivate() {
return this[_private];
}
}
return Demo;
})()
const demo = new Demo();
console.log(demo.getPrivate()); //private
console.log(demo._private); // undefined
- 使用WeakMap
/**
优点:无命名冲突,外部无法修改和访问
缺点:写法复杂,兼容较差,有性能开销
**/
const Demo = (function(){
var _private = new WeakMap() // 私有成员存储容器
class Demo {
constructor() {
_private.set(this, 'private')
}
getPrivate() {
return _private.get(this);
}
}
return Demo;
})()
const demo = new Demo();
console.log(demo.getPrivate()); //private
console.log(demo._private); // undefined
- ES未来提案
class Point {
#x;
#y;
constructor(x, y) {
this.#x = x;
this.#y = y;
}
equals(point) {
return this.#x === point.#x && this.#y === point.#y
}
}
- 使用typescript
private
关键字
class Point {
private number x;
private number y;
constructor(x:number, y:number) {
this.x = x;
this.y = y;
}
equals(point:{x: number, y: number}) {
return this.x === point.x && this.y === point.y
}
}