在另一个文件中访问coffeescript函数

在另一个文件中访问coffeescript函数,coffeescript,Coffeescript,我有一个主要的咖啡脚本代码: <script src="libs/coffeeScript.js"> </script> <script src="maths.coffee"> </script> <script type="text/coffeescript"> document.write math.cube 2 </script> 为什么我不能访问多维数据集功能? 我已经在这个网站上找到了很多解决方案,但都没有成

我有一个主要的咖啡脚本代码:

<script src="libs/coffeeScript.js"> </script>
<script src="maths.coffee"> </script>
<script type="text/coffeescript">

document.write math.cube 2

</script>
为什么我不能访问多维数据集功能?
我已经在这个网站上找到了很多解决方案,但都没有成功。

问题: 当一个CoffeeScript文件被编译成JavaScript时,它被包装在一个IIFE中。因此,最终得到的JS代码如下所示:

(function () {
  var math = {};
  math.cube = function(x) {
    return x * x * x;
  };
})();
这意味着函数的作用域仅限于该IIFE,从而防止了全局命名空间的污染

解决方案: 因为要将CoffeeScript内联,所以需要将要在其他文件中使用的任何函数显式公开到全局对象上,例如
window

math = {}
math.cube = (x) -> x * x * x
window.math = math

或者,您可以事先编译咖啡脚本,并传入
--bare
选项。然后将JavaScript文件包含在页面中。

我尝试了“window.math=math”,但不起作用。对于对象,它也可以在没有“windows.math=math”的情况下工作。它不仅仅适用于函数。我正在使用浏览器(iPad)。
math = {}
math.cube = (x) -> x * x * x
window.math = math