其他 js 无法使用咖啡文件中的函数 [英] functions in coffee-file are not available from other js
问题描述
我尝试在我的 Grails 项目中使用 coffeescript.为了实现这一点,我决定使用 coffeescript-resources 插件.但是结果视图中的已编译咖啡如下所示:
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
关键字,让意外污染全局命名空间变得异常困难.
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 thevar
keyword, make it exceedingly difficult to pollute the global namespace by accident.
如果您想创建顶级变量供其他脚本使用,请将它们作为属性附加到 window 或 CommonJS 中的 exports 对象上.existential operator(如下所述)为您提供了一种可靠的方法来确定在何处添加它们;如果您同时针对 CommonJS 和浏览器: exports ?这个
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')
或
@someFunc = -> alert('hello')
@someFunc
表单假定您位于范围的顶部(即不在另一个函数或类中).
The @someFunc
form assumes that you're at the top of the scope (i.e. not inside another function or class).
或者,您可以找到一种使用 --bare
:
Alternatively, you could find a way to compile your CoffeeScript with --bare
:
-b, --bare
在没有顶级函数安全包装器的情况下编译 JavaScript.
-b, --bare
Compile the JavaScript without the top-level function safety wrapper.
这篇关于其他 js 无法使用咖啡文件中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!