是否可以动态访问模块模式中的私有变量?
有没有办法让模块模式中的公共函数动态访问私有变量? 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
,我最终创建了一个存储我的私有变量的私有变量(一个对象),这样我就能够像这样访问它们
privateVarStore[privateVarName]
但是还有其他解决方案吗?
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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DEMO
是的。
很抱歉让 Adam Rackis 失望,但你可以使用(< strong>evil) eval:
这是应该使用
eval
的少数例外之一。编辑,根据 Hans B PUFAL 建议(评论),您可以并且应该验证
test2
中的参数,如下所示:DEMO
Yes.
Sorry to disappoint Adam Rackis but you can do it with (the evil) eval:
This is one of those few exceptions where
eval
should be used.EDIT, as per Hans B PUFAL suggestion (comment), you can and should validate the parameter in
test2
as follows:否(至少在不诉诸
eval
的情况下,根据qwertymk的回答)。y
不是x
的属性(请考虑将此对象命名为比x
更好的名称,以避免与局部变量x
混淆代码>)。y
是一个局部变量,x
的方法在其上形成了一个闭包。任何
x
的方法都可以访问y
,但不是通过说this.y
,而是通过访问y
> 直接。再次强调,
y
不是对象x
的属性。它只是创建 x 的函数中的一个局部变量,从而导致 x 的方法在其上形成闭包。因此,要让
test2
返回y
,只需执行以下操作:要创建一个允许您访问私有变量的方法,请考虑如下操作:
然后
查看 这个小提琴
No (at least not without resorting to
eval
, per qwertymk's answer).y
is not a property ofx
(consider naming this object something better thanx
to avoid confusion with the local variablex
).y
is a local variable over whichx
's methods have formed a closure.Any of
x
's methods may accessy
, but not by sayingthis.y
, but rather by accessingy
directly.Again,
y
is not a property of your objectx
. It's just a local variable in the function that createdx
, thereby causingx
's methods to form a closure over it.So, to get
test2
to returny
, just do:To create a method allowing you to access private variables, consider something like this:
And then
Check out this fiddle