Javascript定义私有变量

问题描述:

我想用c构建一个类似于javascript的类,主要问题是private属性。Javascript定义私有变量

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检测接入和返回unaccessible,并this.private_var回报5
我的问题是:有没有什么办法可以在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是无法访问? 但

+0

可是什么?看起来你没有完成这个问题。 – Barmar

定义tree的功能,而不是JavaScript对象,通过var关键字定义的函数私有变量,通过this.关键词界定公共取得功能和使用功能

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 
+0

您不会使用ES6类语法显示如何使用它。 – Barmar

+0

谢谢@SolomonTam,定义类的方式将在JavaScript中很好。 –

+0

'所以我不会推荐'?'所以我会推荐' –