我有一个用coffeescript编写的课程,例如,
class Example
constructor: ->
$.each [1, 2, 3], (key, value) =>
@test = value
return @test
render: ->
alert @test
我把这个类作为一个单独的文件,Example.coffee
现在我希望能够像我这样在我的主要javascript文件中实例化:
d = new Example
d.render()
但该类未定义,即使它作为脚本包含在页面上,如
<script src="Example.js></script>
<script src="main.js"></script>
如何让课程公开提供给主文件?
答案 0 :(得分:26)
您可以通过将其声明为window
命名空间来声明您的类是全局可访问的(至少对于浏览器而言):
class window.Example
constructor: ->
$.each [1, 2, 3], (key, value) =>
@test = value
return @test
render: ->
alert @test
这会将Example
直接放入window
。在大多数情况下,您也可以说class @Example
。
默认情况下,CoffeeScript将每个文件包装在(function() { ... })()
包装器中以防止名称空间污染。您可以在编译CoffeeScript时提供-b
来阻止这种情况:
-b, --bare
在没有顶级功能安全包装的情况下编译JavaScript。
但这可能不是你的选择(或者它可能是一个丑陋的选项)。通常的方法是在加载类之前在某处声明一个特定于应用程序的命名空间:
// Probably in a <script> in your top-level HTML...
App = { };
然后适当地命名您的类:
class App.Example
#...
然后通过App
命名空间引用所有内容。
答案 1 :(得分:12)
我知道这是一个旧线程,但是如果其他人发现它有用,请用&#34; @&#34;声明你的课程。并且.js
文件之外的.coffee
文件可以访问它。
所以,在example.coffee
:
class Introverted
honk: ->
alert "This class is visible within the .coffee file but not outside"
class @Extroverted
honk: ->
alert "This class is visible inside and outside of the .coffee file"
编译为example.js
,然后可以在example.html
中使用
<script src="example.js"></script>
<script>
var p = new Extroverted(); // works fine
p.honk();
var i = new Introverted(); // will fail with "Introverted is not defined"
i.honk();
</script>
答案 2 :(得分:4)
创建全局变量
window.Example = Example