1. 使用约定, 默认以_开头 ```javascript // 优点 // 简单、调试方便、兼容性好

    // 缺点 // 外部可访问,命名冲突, class Demo { constructor() { this._private = “private” } getPrivate() { return this._private; } } const demo = new Demo(); console.log(demo.getPrivate()); //private console.log(demo._private);

    1. 2. 使用闭包
    2. ```javascript
    3. /**
    4. 实现1
    5. 优点,没有命令冲突,外部不能访问和修改
    6. 缺点,类构造器逻辑变复杂,方法存在类实例上,子类无法继承,增加性能开销
    7. **/
    8. class Demo {
    9. constructor() {
    10. this._private = "";
    11. _private = "private";
    12. this.getPrivate = function() {return _private};
    13. }
    14. }
    15. const demo = new Demo();
    16. console.log(demo.getPrivate()); //private
    17. console.log(demo._private); // undefined
    18. /**
    19. 实现2
    20. 优点:无命名冲突,外部无法访问和修改
    21. 缺点:写法叫复杂,增加性能开销
    22. **/
    23. const Demo = (function(){
    24. var _private = '';
    25. class Demo {
    26. constructor() {
    27. _private = 'private';
    28. }
    29. getPrivate() {
    30. return _private;
    31. }
    32. }
    33. return Demo;
    34. })()
    35. const demo = new Demo();
    36. console.log(demo.getPrivate()); //private
    37. console.log(demo._private); // undefined
    1. 使用Symbol
    1. /**
    2. 优点,无命名冲突,外部无法访问和修改,无性能损失
    3. 缺点,写法负责,兼容性一般
    4. **/
    5. const Demo = (function(){
    6. var _private = Symbol('private')
    7. class Demo {
    8. constructor() {
    9. this[_private] = 'private';
    10. }
    11. getPrivate() {
    12. return this[_private];
    13. }
    14. }
    15. return Demo;
    16. })()
    17. const demo = new Demo();
    18. console.log(demo.getPrivate()); //private
    19. console.log(demo._private); // undefined
    1. 使用WeakMap
    1. /**
    2. 优点:无命名冲突,外部无法修改和访问
    3. 缺点:写法复杂,兼容较差,有性能开销
    4. **/
    5. const Demo = (function(){
    6. var _private = new WeakMap() // 私有成员存储容器
    7. class Demo {
    8. constructor() {
    9. _private.set(this, 'private')
    10. }
    11. getPrivate() {
    12. return _private.get(this);
    13. }
    14. }
    15. return Demo;
    16. })()
    17. const demo = new Demo();
    18. console.log(demo.getPrivate()); //private
    19. console.log(demo._private); // undefined
    1. ES未来提案
    1. class Point {
    2. #x;
    3. #y;
    4. constructor(x, y) {
    5. this.#x = x;
    6. this.#y = y;
    7. }
    8. equals(point) {
    9. return this.#x === point.#x && this.#y === point.#y
    10. }
    11. }
    1. 使用typescript private关键字
    1. class Point {
    2. private number x;
    3. private number y;
    4. constructor(x:number, y:number) {
    5. this.x = x;
    6. this.y = y;
    7. }
    8. equals(point:{x: number, y: number}) {
    9. return this.x === point.x && this.y === point.y
    10. }
    11. }
    1. 参考ES6 系列之私有变量的实现