Short answer, no, there is no native support for private properties with ES6 classes.(简短的答案,不,ES6类不对私有属性提供本机支持。)
But you could mimic that behaviour by not attaching the new properties to the object, but keeping them inside a class constructor, and use getters and setters to reach the hidden properties.(但是您可以通过不将新属性附加到对象上,而是将它们保留在类构造函数中,并使用getter和setter来访问隐藏的属性来模仿这种行为。)
Note that the getters and setters gets redefine on each new instance of the class.(注意,在类的每个新实例上,getter和setter方法都会重新定义。)
ES6(ES6)
class Person {
constructor(name) {
var _name = name
this.setName = function(name) { _name = name; }
this.getName = function() { return _name; }
}
}
ES5(ES5)
function Person(name) {
var _name = name
this.setName = function(name) { _name = name; }
this.getName = function() { return _name; }
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…