2017-10-13 89 views
0

我想用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

回答

1

定義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

'所以我不會推薦'?'所以我會推薦' –