【发布时间】:2012-07-14 05:29:43
【问题描述】:
我最近重构了我的 JS 代码,偶然发现了这种模式:
APP = (function() {
var x,y,z;
function foo() {}
function bar() {}
return {x:x, y:y, z:z, foo:foo: bar:bar};
})();
这样做的好处是它创建了非全局变量,函数可以访问APP 中定义的所有内容。所以APP.foo可以访问x, y, z和bar而不用输入APP.bar()、APP.x等。也可以通过APP.bar()、APP.x等全局访问所有内容。你也可以嵌套它们:
APP = (function() {
var x,y,z;
function foo() {}
function bar() {}
var WIDGETS = (function() {
var a,b,c;
function hello() {}
function world() {}
return {a:a, b:b, c:c, hello:hello, world:world};
})();
return {x:x, y:y, z:z, foo:foo: bar:bar, WIDGETS:WIDGETS};
})();
所以WIDGETS 可以访问APP 中的变量,但反之则不行(APP.WIDGETS.hello 可以使用foo(),但APP.foo 必须使用WIDGETS.hello())。
我尝试使用 ERB(我在 Rails 上)创建这种模式,但结果很混乱。所以我正在考虑为此编写一个小的源到源编译器——比如 CoffeeScript(具有 SASS 的最小差异/扩展语言哲学),它只是将一些函数编译为替代 javascript。
我只是想要一个速记。
例如,这将编译为我上面的第二个代码块:
//NAMESPACE is a magical function I compile down to the long version in the second code block
APP = NAMESPACE(function() {
var x,y,z;
function foo() {}
function bar() {}
var WIDGETS = NAMESPACE(function() {
var a,b,c;
function hello() {}
function world() {}
//**notice the missing return statement that I don't need to manage and map to my variables**
});
//**notice the missing return statement that I don't need to manage and map to my variables**
});
简单而小巧 - 这样您就无需跟踪变量。还想像这样分隔命名空间(这样我可以将其拆分为多个文件):
APP = NAMESPACE(function() {
var x,y,z;
function foo() {}
function bar() {}
//**notice the missing return statement that I don't need to manage and map to my variables**
});
APP = NAMESPACE(function() {
var WIDGETS = NAMESPACE(function() {
var a,b,c;
function hello() {}
function world() {}
//**notice the missing return statement that I don't need to manage and map to my variables**
});
});
关于如何做到这一点的任何想法?我不确定一切,但我认为如果存在的话,我会更喜欢 Javascript。
【问题讨论】:
-
你可能会疯狂地尝试做这个。看看 Closure Compiler - 那里可能有一些重叠。
-
嗯.. 似乎找不到类似的功能。不过感谢您的参考。
-
附注如果有兴趣,请查看此页面上的答案以了解有关 CC 功能的更多信息。 stackoverflow.com/questions/11486022/what-is-closure-compiler
-
是的,它似乎压缩,删除死代码和优化JS正确...?我正在尝试构建一种可以创建简写语法的东西(据我所知),它超越了 Javascript。
-
您只是用内部变量来描述模块模式,我没有看到您使用的语法有任何特别的好处。
标签: javascript coffeescript namespaces closures