在 Rails3.1.1/Coffeescript 下 - 并不总是获得函数安全包装器
我最近开始将coffescript与Rails一起使用,我发现有时生成的javascript无法获得 函数安全包装。
这是一个演示它的示例项目。
例如,这个CS代码,在index.js.coffee中:
class Foo
afunc: ->
alert("afunc")
正确地变成:
(function() {
var Foo;
Foo = (function() {
function Foo() {}
Foo.prototype.afunc = function() {
return alert("afunc");
};
return Foo;
})();
}).call(this);
但是这个代码,从other.js.coffee:
class App.Func
ouch: ->
alert("ouch")
变成这个未包装的版本
App.Func = (function() {
function Func() {}
Func.prototype.ouch = function() {
return alert("ouch");
};
return Func;
})();
这似乎是由于“应用程序”。前缀 - 我可以看到它会影响命名/范围 - 但为什么 CoffeeScript 会以不同的方式编译它...
应用程序是在 setup.js.coffee 中定义的,如下所示:
window.App =
Models: {}
除非我也将一个类添加到该文件中,否则它也不会被包装。
我确信这一定是我的误解 - 所以提前感谢您对手册的指点:)。
编辑: 我创建了这个问题,因为我认为它可能是我的骨干/咖啡脚本应用程序遇到的一些问题的背后,但似乎事实并非如此。由于该类链接到公共/全局事物“App”,因此它似乎可以工作或不工作。知道为什么会发生仍然很有用 - 是设计使然吗?
I have recently started using coffeescript with Rails and I am finding that sometimes the generated javascript does not get the function safety wrapper.
Here is a sample project demonstrating it.
For example, this CS code, in index.js.coffee:
class Foo
afunc: ->
alert("afunc")
Correctly becomes:
(function() {
var Foo;
Foo = (function() {
function Foo() {}
Foo.prototype.afunc = function() {
return alert("afunc");
};
return Foo;
})();
}).call(this);
But this code, from other.js.coffee:
class App.Func
ouch: ->
alert("ouch")
becomes this un-wrapped version
App.Func = (function() {
function Func() {}
Func.prototype.ouch = function() {
return alert("ouch");
};
return Func;
})();
It seems to be due to the "App." prefix - which I can see affects naming/scope - but why is coffeescript compiling it differently...
App is defined in setup.js.coffee, like this:
window.App =
Models: {}
Which also does not get wrapped, unless I add a class into that file too.
I am sure it must be my misunderstanding - so thanks in advance for the pointers to the manual :).
EDIT:
I created this question as I thought it might be behind some issues I was having with my backbone/coffeescript app, but it seems that it was not. As the class is linked to a public/global thing "App", it seems to work wrapped or not. Still would be useful to know why its happening - is it by design?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在使用的“函数安全包装器”功能可防止在全局命名空间上设置局部变量。由于设置对象属性 (App.Func) 不会影响全局命名空间,因此声明不会包装在函数中。
The "function safety wrapper" feature you are using works to prevent local variables from being set on the global namespace. Since setting an object property (App.Func) doesn't affect the global namespace, the declaration is not wrapped in a function.