functions in coffee-file are not available from other js

痞子三分冷 提交于 2019-12-04 02:39:02

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/19337111/functions-in-coffee-file-are-not-available-from-other-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!