我可以向闭包添加方法吗
这是闭包要避免的,但我想知道是否有办法向闭包添加方法。基本上我有一个 js 文件库,我想通过添加新方法来为特定客户端增强该库。
我有一个名为 Library 的 js 文件:
var LIBRARY = (function(){
var name;
return {
setName: function(n) { name = n; }
}());
但对于新客户,我想给他们一个新的 js 文件,该文件只会增强 LIBRARY,添加一个新功能:
function(first, last){
name = first + " " + last;
}
但我不想修改库 js。有什么方法可以将此函数附加到 LIBRARY 以便该函数具有对 name 变量的必要访问权限吗?
This is sort of what closures are meant to avoid, but I'm wondering if there's a way to a add a method to a closure. Basically I have a js file library that I'd like to augment for a specific client by adding a new method.
I have a js file called library:
var LIBRARY = (function(){
var name;
return {
setName: function(n) { name = n; }
}());
but for a new client I want to give them a new js file that will just augment LIBRARY, adding a new function:
function(first, last){
name = first + " " + last;
}
I don't want to have to modify the library js though. Is there any way to append this function to LIBRARY so that the function has the necessary access to the name variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,不幸的是你不能——或者至少不能以合理的方式。只有在该闭包中定义的函数才能访问该局部变量。
不合理的方法是使用
eval
玩游戏,但我强烈建议不要这样做。您所能做的就是向 LIBRARY 添加不需要直接访问该变量的函数。
No, unfortunately you can't — or at least, not in a reasonable way. Only the functions defined within that closure will have access to that local variable.
The unreasonable way to do this would be to play games with
eval
, but I'd strongly advise against it.All you can do is add functions to
LIBRARY
that don't need direct access to that variable.不确定您到底如何设想“附加”,但这有效
Not sure exactly how you envisioned the "appending", but this works
所以我只是想记录下我是如何实现这一目标的,因为它强调了一种不同的 JS 架构思考方式。
如前所述,我希望能够通过客户特定的功能来增强我的库。我最终做的是修改我的库以读取如下内容:
然后客户端库使用如下函数增强我的库:
所以现在客户端代码可以调用:
并且名称将设置为“静态河马” ”
So I just wanted to leave a note on how I actually accomplished this because it underscores a different way of thinking about architecture in JS.
As mentioned, I wanted to be able to augment my library with client-specific functions. What I ended up doing was modifying my library to read something like:
Then the client library augments my LIBRARY with a function like so:
so now client code can call:
and name will be set to "static hippo"