Javascript 定义私有变量

Javascript define private variable

我想像在 c 中一样使用 javascript 构建一个 class,主要问题是 private 属性。

var tree = {
  private_var: 5,
  getPrivate:function(){
   return this.private_var;
  }
};
console.log(tree.private_var);//5 this line want to return unaccessible
console.log(tree.getPrivate());//5

所以我想检测来自tree.private_var和returnunaccessiblethis.private_varreturn5.[=27的访问=] 我的问题是:有没有办法在 javascript 中设置私有属性?

编辑:我是这样看的

class Countdown {
    constructor(counter, action) {
        this._counter = counter;
        this._action = action;
    }
    dec() {
        if (this._counter < 1) return;
        this._counter--;
        if (this._counter === 0) {
            this._action();
        }
    }
}
CountDown a;

a._counter 无法访问? 但是

tree定义为函数而不是JavaScript对象,通过var关键字在函数中定义私有变量,通过[=14=定义public获取函数]关键字并使用函数

创建一个新实例
var Tree = function(){
    var private_var = 5;
    this.getPrivate = function(){
        return private_var;
    }
}

var test = new Tree();
test.private_var; //return undefined
test.getPrivate(); //return 5

在 ES6 中,您可以这样做,但是 IE 不支持它,所以我不推荐

class Tree{
    constructor(){
        var private_var =5;
        this.getPrivate = function(){ return private_var }

    }
}

var test = new Tree();
test.private_var; //return undefined
test.getPrivate(); //return 5