[英]Is it possible to access private variables in a module pattern dynamically?
Is there a way to have a public function from the module-pattern accessing private variables dynamically? 有没有办法从模块模式中动态访问私有变量的公共函数? test1 shows what I mean with "access dynamically" but with public variables
test1显示了我对“动态访问”的含义,但使用了公共变量
var x = (function(){
var x=0, y=2, z=5;
return {
toast: 123,
test1: function(arg){
return this[arg];
},
test2: function(){
// ??
}
};
}());
console.log(x.test1("toast")); // 123
console.log(x.test2("y")); // should return 2
I ended up with creating a single private variable (an object) storing my private variables so I was able to access them like that 我最终创建了一个存储我的私有变量的私有变量(一个对象),所以我能够像这样访问它们
privateVarStore[privateVarName]
But is there another solution for that? 但是有另一种解决方案吗?
Yes. 是。
Sorry to disappoint Adam Rackis but you can do it with (the evil ) eval: 很抱歉让Adam Rackis失望,但你可以用( 邪恶的 )eval做到这一点:
var x = (function(){
var x=0, y=2, z=5;
return {
toast: 123,
test1: function(arg){
return this[arg];
},
test2: function(a){
return eval(a)
}
};
}());
console.log(x.test1("toast")); // 123
console.log(x.test2("y")); // should return 2 -> does return 2
This is one of those few exceptions where eval
should be used. 这是应该使用
eval
少数例外之一。
EDIT, as per Hans B PUFAL suggestion (comment), you can and should validate the parameter in test2
as follows: 编辑,根据Hans B PUFAL建议(评论),您可以并且应该在
test2
验证参数,如下所示:
test2: function(a){
return /^[$_a-z][$_a-z0-9]*$/i.test (a) ? eval(a) : undefined;
}
No (at least not without resorting to eval
, per qwertymk's answer). 不 (至少不是没有诉诸
eval
,根据qwertymk的回答)。
y
is not a property of x
(consider naming this object something better than x
to avoid confusion with the local variable x
). y
不是x
的属性(考虑将此对象命名为比x
更好的东西,以避免与局部变量x
混淆)。 y
is a local variable over which x
's methods have formed a closure. y
是一个局部变量, x
的方法形成了一个闭包。
Any of x
's methods may access y
, but not by saying this.y
, but rather by accessing y
directly. 任何
x
的方法可以访问y
,但不应该说this.y
,而是通过访问y
直接。
Again, y
is not a property of your object x
. 同样,
y
不是对象x
的属性 。 It's just a local variable in the function that created x
, thereby causing x
's methods to form a closure over it. 它只是函数中创建
x
的局部变量,从而导致x
的方法在其上形成闭包。
So, to get test2
to return y
, just do: 所以,要让
test2
返回y
,只需:
test2: function(){
return y;
}
To create a method allowing you to access private variables, consider something like this: 要创建允许您访问私有变量的方法,请考虑以下内容:
var x = (function () {
var privateMembers = { x: 0, y: 2, z: 5 };
return {
getPrivate: function (name) {
return privateMembers[name];
},
toast: 123,
test1: function (arg) {
return this[arg];
},
test2: function () {
// ??
}
};
})();
And then 接着
alert(x.getPrivate("y")); //alerts 2
Check out this fiddle 看看这个小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.