如何将外部变量传递给私有 javascript 外部闭包函数?
我可能在这方面做出了一些糟糕的设计选择。我有几个像这样实例化的对象。
core.modules.trial = function(sandbox){
return{
alert_private : function(){
alert(omgpi);
}
};
};
我想这样做:
core.modules.trial[omgpi] = "external private var";
var trial = core.modules.trial();
trial.alert_private(); //would hopefully output "external private var"
我试图将 omgpi 变量分配给外部函数的私有范围。通常,您会在返回任何内容之前在外部函数中执行 var omgpi 。但当调用此函数时,我尝试从外部脚本执行此操作
I may have made some poor design choices on this one. I have several objects being instanced like this.
core.modules.trial = function(sandbox){
return{
alert_private : function(){
alert(omgpi);
}
};
};
I would like to do this:
core.modules.trial[omgpi] = "external private var";
var trial = core.modules.trial();
trial.alert_private(); //would hopefully output "external private var"
I am trying to assign the omgpi variable to the private scope of the outer function. Normally you would do var omgpi within the outer function before returning anything. But I am trying to do this from an external script when this function is called
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以猴子修补 core.modules.Trial:
请参阅 call 的文档。
You can monkey-patch core.modules.trial:
See the documentation for call.
这是你想要的吗?
Is this what you want?
如果您需要 omgpi 位于闭包中,则需要从内部设置它。你不能在你不参与的闭包中设置东西。
但每当您调用 core.modules.Trial() 时,
this
都会引用 modules,因为它就像父级。因此,您可以将值粘贴在模块中,如下所示:然后剩下的就可以了:
顺便说一句,您的原始代码有一个错误:
它使用变量 omgpi 的值作为键。您需要
core.modules.Trial.omgpi
或core.modules.Trial["omgpi"]
。If you need omgpi to be in the closure, you need to set it from within. You can't set things in closures you're not a part of.
But whenever you call core.modules.trial(),
this
refers to modules because that's like the parent. So you could stick the value in modules like this:Then the rest works:
By the way, your original code had a bug:
This uses the value of the variable omgpi as the key. You want either
core.modules.trial.omgpi
orcore.modules.trial["omgpi"]
.