- 原文地址:Private Variables in JavaScript
- 原文做者:Marcus Noble
- 译文出自:掘金翻译计划
- 本文永久连接:github.com/xitu/gold-m…
- 译者:Noah Gao
- 校对者:老教授 ryouaki
最近 JavaScript 有了不少改进,新的语法和功能一直在被增长进来。但有些东西并无改变,一切仍然是对象,几乎全部东西均可以在运行时被改变,而且没有公共、私有属性的概念。可是咱们本身能够用一些技巧来改变这种状况,在这篇文章中,我介绍各类能够实现私有变量的方式。javascript
在 2015 年,JavaScript 有了 类 ,对于那些从 更传统的 C 语系语言(如 Java 和 C#)过来的程序员们,他们会更熟悉这种操做对象的方式。可是很明显,这些类不像你习惯的那样 -- 它的属性没有修饰符来控制访问,而且全部属性都须要在函数中定义。html
那么咱们如何才能保护那些不该该在运行时被改变的数据呢?咱们来看看一些选项。前端
在整篇文章中,我将反复用到一个用于构建形状的示例类。它的宽度和高度只能在初始化时设置,提供一个属性来获取面积。有关这些示例中使用的
get
关键字的更多信息,请参阅我以前的文章 Getters 和 Setters。java
第一个也是最成熟的方法是使用特定的命名约定来表示属性应该被视为私有。一般如下划线做为属性名称的前缀(例如 _count
)。这并无真正阻止变量被访问或修改,而是依赖于开发者之间的相互理解,认为这个变量应该被视为限制访问。android
class Shape {
constructor(width, height) {
this._width = width;
this._height = height;
}
get area() {
return this._width * this._height;
}
}
const square = new Shape(10, 10);
console.log(square.area); // 100
console.log(square._width); // 10
复制代码
想要稍有一些限制性,您可使用 WeakMap 来存储全部私有值。这仍然不会阻止对数据的访问,但它将私有值与用户可操做的对象分开。对于这种技术,咱们将 WeakMap 的关键字设置为私有属性所属对象的实例,而且咱们使用一个函数(咱们称之为 internal
)来建立或返回一个对象,全部的属性将被存储在其中。这种技术的好处是在遍历属性时或者在执行 JSON.stringify
时不会展现出实例的私有属性,但它依赖于一个放在类外面的能够访问和操做的 WeakMap 变量。ios
const map = new WeakMap();
// 建立一个在每一个实例中存储私有变量的对象
const internal = obj => {
if (!map.has(obj)) {
map.set(obj, {});
}
return map.get(obj);
}
class Shape {
constructor(width, height) {
internal(this).width = width;
internal(this).height = height;
}
get area() {
return internal(this).width * internal(this).height;
}
}
const square = new Shape(10, 10);
console.log(square.area); // 100
console.log(map.get(square)); // { height: 100, width: 100 }
复制代码
Symbol 的实现方式与 WeakMap 十分相近。在这里,咱们可使用 Symbol 做为 key 的方式建立实例上的属性。这能够防止该属性在遍历或使用 JSON.stringify
时可见。不过这种技术须要为每一个私有属性建立一个 Symbol。若是您在类外能够访问该 Symbol,那你仍是能够拿到这个私有属性。git
const widthSymbol = Symbol('width');
const heightSymbol = Symbol('height');
class Shape {
constructor(width, height) {
this[widthSymbol] = width;
this[heightSymbol] = height;
}
get area() {
return this[widthSymbol] * this[heightSymbol];
}
}
const square = new Shape(10, 10);
console.log(square.area); // 100
console.log(square.widthSymbol); // undefined
console.log(square[widthSymbol]); // 10
复制代码
到目前为止所显示的全部技术仍然容许从类外访问私有属性,闭包为咱们提供了一种解决方法。若是您愿意,能够将闭包与 WeakMap 或 Symbol 一块儿使用,但这种方法也能够与标准 JavaScript 对象一块儿使用。闭包背后的想法是将数据封装在调用时建立的函数做用域内,可是从内部返回函数的结果,从而使这一做用域没法从外部访问。程序员
function Shape() {
// 私有变量集
const this$ = {};
class Shape {
constructor(width, height) {
this$.width = width;
this$.height = height;
}
get area() {
return this$.width * this$.height;
}
}
return new Shape(...arguments);
}
const square = new Shape(10, 10);
console.log(square.area); // 100
console.log(square.width); // undefined
复制代码
这种技术存在一个小问题,咱们如今存在两个不一样的 Shape
对象。代码将调用外部的 Shape
并与之交互,但返回的实例将是内部的 Shape
。这在大多数状况下可能不是什么大问题,但会致使 square instanceof Shape
表达式返回 false
,这可能会成为代码中的问题所在。github
解决这一问题的方法是将外部的 Shape 设置为返回实例的原型:typescript
return Object.setPrototypeOf(new Shape(...arguments), this);
复制代码
不幸的是,这还不够,只更新这一行如今会将 square.area
视为未定义。这是因为 get
关键字在幕后工做的缘故。咱们能够经过在构造函数中手动指定 getter 来解决这个问题。
function Shape() {
// 私有变量集
const this$ = {};
class Shape {
constructor(width, height) {
this$.width = width;
this$.height = height;
Object.defineProperty(this, 'area', {
get: function() {
return this$.width * this$.height;
}
});
}
}
return Object.setPrototypeOf(new Shape(...arguments), this);
}
const square = new Shape(10, 10);
console.log(square.area); // 100
console.log(square.width); // undefined
console.log(square instanceof Shape); // true
复制代码
或者,咱们能够将 this
设置为实例原型的原型,这样咱们就能够同时使用 instanceof
和 get
。在下面的例子中,咱们有一个原型链 Object -> 外部的 Shape -> 内部的 Shape 原型 -> 内部的 Shape
。
function Shape() {
// 私有变量集
const this$ = {};
class Shape {
constructor(width, height) {
this$.width = width;
this$.height = height;
}
get area() {
return this$.width * this$.height;
}
}
const instance = new Shape(...arguments);
Object.setPrototypeOf(Object.getPrototypeOf(instance), this);
return instance;
}
const square = new Shape(10, 10);
console.log(square.area); // 100
console.log(square.width); // undefined
console.log(square instanceof Shape); // true
复制代码
Proxy 是 JavaScript 中一项美妙的新功能,它将容许你有效地将对象包装在名为 Proxy 的对象中,并拦截与该对象的全部交互。咱们将使用 Proxy 并遵守上面的 命名约定
来建立私有变量,但可让这些私有变量在类外部访问受限。
Proxy 能够拦截许多不一样类型的交互,但咱们要关注的是 get
和 set
,Proxy 容许咱们分别拦截对一个属性的读取和写入操做。建立 Proxy 时,你将提供两个参数,第一个是您打算包裹的实例,第二个是您定义的但愿拦截不一样方法的 “处理器” 对象。
咱们的处理器将会看起来像是这样:
const handler = {
get: function(target, key) {
if (key[0] === '_') {
throw new Error('Attempt to access private property');
}
return target[key];
},
set: function(target, key, value) {
if (key[0] === '_') {
throw new Error('Attempt to access private property');
}
target[key] = value;
}
};
复制代码
在每种状况下,咱们都会检查被访问的属性的名称是否如下划线开头,若是是的话咱们就抛出一个错误从而阻止对它的访问。
class Shape {
constructor(width, height) {
this._width = width;
this._height = height;
}
get area() {
return this._width * this._height;
}
}
const handler = {
get: function(target, key) {
if (key[0] === '_') {
throw new Error('Attempt to access private property');
}
return target[key];
},
set: function(target, key, value) {
if (key[0] === '_') {
throw new Error('Attempt to access private property');
}
target[key] = value;
}
}
const square = new Proxy(new Shape(10, 10), handler);
console.log(square.area); // 100
console.log(square instanceof Shape); // true
square._width = 200; // 错误:试图访问私有属性
复制代码
正如你在这个例子中看到的那样,咱们保留使用 instanceof
的能力,也就不会出现一些意想不到的结果。
不幸的是,当咱们尝试执行 JSON.stringify
时会出现问题,由于它试图对私有属性进行格式化。为了解决这个问题,咱们须要重写 toJSON
函数来仅返回“公共的”属性。咱们能够经过更新咱们的 get 处理器来处理 toJSON
的特定状况:
注:这将覆盖任何自定义的
toJSON
函数。
get: function(target, key) {
if (key[0] === '_') {
throw new Error('Attempt to access private property');
} else if (key === 'toJSON') {
const obj = {};
for (const key in target) {
if (key[0] !== '_') { // 只复制公共属性
obj[key] = target[key];
}
}
return () => obj;
}
return target[key];
}
复制代码
咱们如今已经封闭了咱们的私有属性,而预计的功能仍然存在,惟一的警告是咱们的私有属性仍然可被遍历。for(const key in square)
会列出 _width
和 _height
。谢天谢地,这里也提供一个处理器!咱们也能够拦截对 getOwnPropertyDescriptor
的调用并操做咱们的私有属性的输出:
getOwnPropertyDescriptor(target, key) {
const desc = Object.getOwnPropertyDescriptor(target, key);
if (key[0] === '_') {
desc.enumerable = false;
}
return desc;
}
复制代码
如今咱们把全部特性都放在一块儿:
class Shape {
constructor(width, height) {
this._width = width;
this._height = height;
}
get area() {
return this._width * this._height;
}
}
const handler = {
get: function(target, key) {
if (key[0] === '_') {
throw new Error('Attempt to access private property');
} else if (key === 'toJSON') {
const obj = {};
for (const key in target) {
if (key[0] !== '_') {
obj[key] = target[key];
}
}
return () => obj;
}
return target[key];
},
set: function(target, key, value) {
if (key[0] === '_') {
throw new Error('Attempt to access private property');
}
target[key] = value;
},
getOwnPropertyDescriptor(target, key) {
const desc = Object.getOwnPropertyDescriptor(target, key);
if (key[0] === '_') {
desc.enumerable = false;
}
return desc;
}
}
const square = new Proxy(new Shape(10, 10), handler);
console.log(square.area); // 100
console.log(square instanceof Shape); // true
console.log(JSON.stringify(square)); // "{}"
for (const key in square) { // No output
console.log(key);
}
square._width = 200; // 错误:试图访问私有属性
复制代码
Proxy 是现阶段我在 JavaScript 中最喜欢的用于建立私有属性的方法。这种类是以老派 JS 开发人员熟悉的方式构建的,所以能够经过将它们包装在相同的 Proxy 处理器来兼容旧的现有代码。
TypeScript 是 JavaScript 的一个超集,它会编译为原生 JavaScript 用在生产环境。容许指定私有的、公共的或受保护的属性是 TypeScript 的特性之一。
class Shape {
private width;
private height;
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
}
const square = new Shape(10, 10)
console.log(square.area); // 100
复制代码
使用 TypeScript 须要注意的重要一点是,它只有在 编译 时才获知这些类型,而私有、公共修饰符在编译时才有效果。若是你尝试访问 square.width
,你会发现,竟然是能够的。只不过 TypeScript 会在编译时给你报出一个错误,但不会中止它的编译。
// 编译时错误:属性 ‘width’ 是私有的,只能在 ‘Shape’ 类中访问。
console.log(square.width); // 10
复制代码
TypeScript 不会自做聪明,不会作任何的事情来尝试阻止代码在运行时访问私有属性。我只把它列在这里,也是让你们意识到它并不能直接解决问题。你能够 本身观察一下 由上面的 TypeScript 建立出的 JavaScript 代码。
我已经向你们介绍了如今可使用的方法,但将来呢?事实上,将来看起来颇有趣。目前有一个提案,向 JavaScript 的类中引入 private fields,它使用 #
符号表示它是私有的。它的使用方式与命名约定技术很是相似,但对变量访问提供了实际的限制。
class Shape {
#height;
#width;
constructor(width, height) {
this.#width = width;
this.#height = height;
}
get area() {
return this.#width * this.#height;
}
}
const square = new Shape(10, 10);
console.log(square.area); // 100
console.log(square instanceof Shape); // true
console.log(square.#width); // 错误:私有属性只能在类中访问
复制代码
若是你对此感兴趣,能够阅读如下 完整的提案 来获得更接近事实真相的细节。我以为有趣的一点是,私有属性须要预先定义,不能临时建立或销毁。对我来讲,这在 JavaScript 中感受像是一个很是陌生的概念,因此看看这个提案如何继续发展将变得很是有趣。目前,这一提案更侧重于私有的类属性,而不是私有函数或对象层面的私有成员,这些可能会晚一些出炉。
在写这篇文章时,我还发布了一个 NPM 包来帮助建立私有属性 -- privatise。我使用了上面介绍的 Proxy 方法,并增长额外的处理器以容许传入类自己而不是实例。全部代码均可以在 GitHub 上找到,欢迎你们提出任何 PR 或 Issue。
掘金翻译计划 是一个翻译优质互联网技术文章的社区,文章来源为 掘金 上的英文分享文章。内容覆盖 Android、iOS、前端、后端、区块链、产品、设计、人工智能等领域,想要查看更多优质译文请持续关注 掘金翻译计划、官方微博、知乎专栏。