我尝试在我的Grails项目中使用coffeescript。 为了实现这个目标,我决定使用coffeescript-resources插件。 但结果视图中的编译咖啡如下所示:
(function() { var someFunc; someFunc = function() { return alert("hello"); }; }).call(this);在这种情况下,我不能称之为。 我没有在插件文档中找到任何正确的配置,以避免在编译coffee-file时使用匿名函数。 我怎么解决这个问题?
I try to use coffeescript in my Grails-project. To achive this I decided to use coffeescript-resources plugin. But compiled coffee in result view looks like follows:
(function() { var someFunc; someFunc = function() { return alert("hello"); }; }).call(this);and in this case I cant call it. I have not found any proper configurations in the plugin documentation to avoid using anonymous functions while compiling coffee-file. How can I solve this?
最满意答案
从精细手册 :
词汇范围和可变安全 [...] 虽然为了清楚起见在本文档中进行了抑制,但所有CoffeeScript输出都包含在一个匿名函数中: (function(){ ... })(); 这个安全包装器与var关键字的自动生成相结合,使得非常难以意外地污染全局命名空间。
如果要为其他要使用的脚本创建顶级变量,请将它们作为属性附加到窗口或CommonJS中的exports对象上。 存在运算符 (如下所述)为您提供了一种可靠的方法来确定添加它们的位置; 如果你的目标是CommonJS和浏览器: exports ? this exports ? this
因此,存在自调用函数包装器以防止您污染全局命名空间。 如果你想把东西放到全局命名空间中,那么你必须明确地把它放在那里; 在浏览器中,您可以使用:
window.someFunc = -> alert('hello')要么
@someFunc = -> alert('hello')@someFunc表单假设您位于范围的顶部(即不在另一个函数或类中)。
或者,您可以找到一种使用--bare编译CoffeeScript的方法:
-b, --bare 在没有顶级功能安全包装的情况下编译JavaScript。
From the fine manual:
Lexical Scoping and Variable Safety [...] Although suppressed within this documentation for clarity, all CoffeeScript output is wrapped in an anonymous function: (function(){ ... })(); This safety wrapper, combined with the automatic generation of the var keyword, make it exceedingly difficult to pollute the global namespace by accident.
If you'd like to create top-level variables for other scripts to use, attach them as properties on window, or on the exports object in CommonJS. The existential operator (covered below), gives you a reliable way to figure out where to add them; if you're targeting both CommonJS and the browser: exports ? this
So that self-invoking function wrapper exists to prevent you from polluting the global namespace. If you want to put something into the global namespace then you have to put it there explicitly; in a browser, you can do that using:
window.someFunc = -> alert('hello')or
@someFunc = -> alert('hello')The @someFunc form assumes that you're at the top of the scope (i.e. not inside another function or class).
Alternatively, you could find a way to compile your CoffeeScript with --bare:
-b, --bare Compile the JavaScript without the top-level function safety wrapper.
更多推荐
发布评论