2015-10-12 42 views
0

如何在構造函數中使用公共公共函數訪問私有變量。如何在構造函數中使用通用公共函數訪問私有變量

function construct(){ 

    var priValue1 = 0; 
    var priValue2 = 0; 
    var priValue3 = 0;  

    this.getvalue = function(_input){ 
     return this[_input]; 
    } 

} 

construct.prototype.init = function(){ 
    if(this.getvalue("priValue1")){ 
     console.log("Value 1") 
    } 
} 

var nc = new construct(); 
nc.init(); 

無法訪問私有變量。

+1

'返回_input'取代'返回此[_Input]' –

+0

http://jsfiddle.net/sandenay/0ac78v7d/ –

+0

@ SandeepNayak我認爲這不會起作用。這隻會返回傳入的參數。我認爲他們想訪問他們聲明的變量。 –

回答

4

您可以將您的私有變量存儲在一個對象中,並通過屬性名稱訪問它們。

function construct(){ 
 
    var priVars = { 
 
     priValue1: 0, 
 
     priValue2: 0, 
 
     priValue3: 0 
 
    }; 
 

 
    this.getvalue = function(_input){ 
 
     return priVars[_input]; 
 
    } 
 

 
} 
 

 
construct.prototype.init = function(){ 
 
    if(this.getvalue("priValue1")){ 
 
     console.log("Value 1") 
 
    } 
 
} 
 

 
var nc = new construct(); 
 
nc.init();

0

當你申報了「私人變種」這不是存儲在this,變量是入店的範圍變量。使用自己的代碼,我會寫

this.getvalue = function(_input){ 
    return eval(_input); 
} 

來獲取值動態

+0

Eww ...如果'eval'是答案,那麼問題是錯誤的。 –

+0

也許問題是錯誤的,因爲你沒有javascript上的私有變量;)使用一個對象它也很好! – sminutoli

相關問題