Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

javascript - JavaScript ES6类中的私有属性(Private properties in JavaScript ES6 classes)

Is it possible to create private properties in ES6 classes?(是否可以在ES6类中创建私有属性?)

Here's an example.(这是一个例子。)

How can I prevent access to instance.property ?(如何防止访问instance.property ?)
class Something {
  constructor(){
    this.property = "test";
  }
}

var instance = new Something();
console.log(instance.property); //=> "test"
  ask by d13 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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; }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...