![](/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.