如何使用ES6中的私有变量? [英] How to work with private variables in ES6?
问题描述
在ES5中,您可以使用以下私有和公共变量来模拟类:
In ES5, you could emulate a class with private and public variables like this:
car.js
function Car() {
// using var causes speed to be only available inside Car (private)
var speed = 10;
// public variable - still accessible outside Car
this.model = "Batmobile";
// public method
this.init = function(){
}
}
但是在ES6中,你不能再在构造函数之外声明vars,所以它实际上是HARDER以一种OOP方式处理类!
But in ES6, you can no longer declare vars outside the constructor, making it actually HARDER to work with classes in a OOP way!?
您可以在构造函数中使用this来声明变量,但是默认情况下它们是public的。这很奇怪,因为ES6 DOES 有一个get / set关键字!
You can declare variables in the constructor using this, but that makes them public by default. This is very weird since ES6 DOES have a get / set keyword!
class Vehicle {
constructor(make, year) {
// the underscore is nice, but these are still public!
this._make = make;
this._year = year;
}
// get and set can be handy, but would make more sense
// if _make and _year were not accessible any other way!
get make() {
return this._make;
}
get year() {
return this._year;
}
}
推荐答案
ES6标准不提供定义私有变量的新方法。
ES6 standard does not offer a new way for defining private variables.
这是一个事实,新的ES6 类基于构造函数。
It's a fact, that new ES6 class is simply syntactic sugar around regular prototype-based constructors.
get 和 set 关键字提供了一种简单定义先前定义的ES5自定义getter和setter的方法使用 Object.defineProperty()的描述符
get and set keywords are offering a way for simplified definition of ES5 custom getters and setters that were previously defined with a descriptor of Object.defineProperty()
下面的示例使用WeakMap来存储私有属性。
The example below features the use of a WeakMap for storing private properties.
// myModule.js
const first_name = new WeakMap();
class myClass {
constructor (firstName) {
first_name.set(this, firstName);
}
get name() {
return first_name.get(this);
}
}
export default myClass;
我指的是由David Vujic撰写的文章什么?等待。真?不好了! (关于ES6课程和隐私的帖子)与使用WeakMaps的想法。
I'm referring to article, written by David Vujic What? Wait. Really? Oh no! (a post about ES6 classes and privacy) with the idea of using WeakMaps.
这篇关于如何使用ES6中的私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!