咖啡文件中的函数不能从其他js [英] functions in coffee-file are not available from other js

查看:126
本文介绍了咖啡文件中的函数不能从其他js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在我的Grails项目中使用coffeescript。为了achive这个我决定使用coffeescript资源插件。但在结果视图中编译的咖啡如下:

 (function(){
var someFunc;
someFunc = function(){
return alert(hello);
};
})call(this);

在这种情况下我不能调用它。我没有在插件文档中找到任何适当的配置,以避免在编译coffee文件时使用匿名函数。我如何解决这个问题?

解决方案

fine manual


词法范围和变量安全 >
[...]

虽然为了清楚起见在本文档中被禁止,但所有CoffeeScript输出都包含在一个匿名函数中:(function(){...} )(); 这个安全包装,结合自动生成 var 关键字,使得极其难以意外地污染全局命名空间。



如果您要为要使用的其他脚本创建顶级变量,请在窗口导出对象。 存在操作符(如下所述),为您提供了一种可靠的方法来确定添加它们的位置;如果您同时定位CommonJS和浏览器: exports?此


因此自调用函数包装器存在以防止污染全局命名空间。如果你想把东西放到全局命名空间中,你必须明确地把它放在那里;在浏览器中,你可以使用:

  window.someFunc =  - > alert('hello')



p $ p> @someFunc = - > alert('hello')

@someFunc form假定你在范围的顶部(即不在另一个函数或类中)。



或者,你可以找到一种方法来编译你的CoffeeScript - bare


-b,--bare

编译JavaScript而不使用 top -level function safety wrapper



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?

解决方案

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.

这篇关于咖啡文件中的函数不能从其他js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆