Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES6 系列之私有变量的实现 #83

Open
yangtao2o opened this issue Apr 6, 2020 · 0 comments
Open

ES6 系列之私有变量的实现 #83

yangtao2o opened this issue Apr 6, 2020 · 0 comments

Comments

@yangtao2o
Copy link
Owner

yangtao2o commented Apr 6, 2020

ES6 系列之私有变量的实现

  1. 约定

实现

class Example {
  constructor() {
    this._private = "private";
  }
  getName() {
    return this._private;
  }
}

var ex = new Example();

console.log(ex.getName()); // private
console.log(ex._private); // private

优点

  • 写法简单
  • 调试方便
  • 兼容性好

缺点

  • 外部可以访问和修改
  • 语言没有配合的机制,如 for in 语句会将所有属性枚举出来
  • 命名冲突
  1. 闭包
class Example {
  constructor() {
    var _private = "";
    _private = "private";
    this.getName = function() {
      return _private;
    };
  }
}

var ex = new Example();

console.log(ex.getName()); // private
console.log(ex._private); // undefined

优点

  • 无命名冲突
  • 外部无法访问和修改

缺点

  • constructor 的逻辑变得复杂。构造函数应该只做对象初始化的事情,现在为了实现私有变量,必须包含部分方法的实现,代码组织上略不清晰。
  • 方法存在于实例,而非原型上,子类也无法使用 super 调用
  • 构建增加一点点开销
  1. Symbol
const Example = (function() {
  var _private = Symbol("private");

  class Example {
    constructor() {
      this[_private] = "private";
    }
    getName() {
      return this[_private];
    }
  }

  return Example;
})();

var ex = new Example();

console.log(ex.getName()); // private
console.log(ex._private); // undefined

优点

  • 无命名冲突
  • 外部无法访问和修改
  • 无性能损失

缺点

  • 写法稍微复杂
  • 兼容性也还好
  1. WeakMap
const Example = (function() {
  var _private = new WeakMap(); // 私有成员存储容器

  class Example {
    constructor() {
      _private.set(this, "private");
    }
    getName() {
      return _private.get(this);
    }
  }

  return Example;
})();

var ex = new Example();

console.log(ex.getName()); // private
console.log(ex._private); // undefined

优点

  • 无命名冲突
  • 外部无法访问和修改

缺点

  • 写法比较麻烦
  • 兼容性有点问题
  • 有一定性能代价
  1. 最新提案
class Point {
  #x;
  #y;

  constructor(x, y) {
    this.#x = x;
    this.#y = y;
  }

  equals(point) {
    return this.#x === point.#x && this.#y === point.#y;
  }
}

原文链接:ES6 系列之私有变量的实现

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant