简体   繁体   English

如何在构造函数中使用公共公用函数访问私有变量

[英]How to access a private variables using a common public function within the constructor

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();

Couldn't get access for the private variable. 无法访问私有变量。

You could store your private variables in an object, and access them by property name. 您可以将私有变量存储在对象中,然后按属性名称访问它们。

 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(); 

When you declare a "private var" this is not stored on this , the variable is accesible as a scope variable. 声明“私有变量”时,该变量未存储在this ,该变量可以用作作用域变量。 Using your own code I would write 使用您自己的代码,我会写

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

to get the value dynamically 动态获得价值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM