![](/img/trans.png)
[英]How to access private variable using a public method within same object in javascript?
[英]How to access a private variables using a common public function within the constructor
如何在構造函數中使用公共公用函數訪問私有變量。
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();
無法訪問私有變量。
您可以將私有變量存儲在對象中,然后按屬性名稱訪問它們。
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();
聲明“私有變量”時,該變量未存儲在this
,該變量可以用作作用域變量。 使用您自己的代碼,我會寫
this.getvalue = function(_input){
return eval(_input);
}
動態獲得價值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.