Lac*_*ose 12 javascript coffeescript
我有一个用coffeescript编写的课程,例如,
class Example
constructor: ->
$.each [1, 2, 3], (key, value) =>
@test = value
return @test
render: ->
alert @test
Run Code Online (Sandbox Code Playgroud)
我把这个类作为一个单独的文件,Example.coffee
现在我希望能够在我的主要javascript文件中实例化,如下所示:
d = new Example
d.render()
Run Code Online (Sandbox Code Playgroud)
但是,即使将类作为脚本包含在页面上,类也是未定义的,例如
<script src="Example.js></script>
<script src="main.js"></script>
Run Code Online (Sandbox Code Playgroud)
如何让课程公开提供给主文件?
mu *_*ort 26
您可以通过将其声明为window名称空间来声明您的类是全局可访问的(至少对于浏览器而言):
class window.Example
constructor: ->
$.each [1, 2, 3], (key, value) =>
@test = value
return @test
render: ->
alert @test
Run Code Online (Sandbox Code Playgroud)
这将Example直接进入window.class @Example在大多数情况下,您也可以说.
默认情况下,CoffeeScript将每个文件(function() { ... })()包装在包装器中以防止名称空间污染.您可以通过-b在编译CoffeeScript时提供来防止这种情况:
-b, --bare
在没有顶级功能安全包装的情况下编译JavaScript.
但这对你来说可能不是一个选择(或者它可能是一个丑陋的选择).通常的方法是在加载类之前在某处声明一个特定于应用程序的命名空间:
// Probably in a <script> in your top-level HTML...
App = { };
Run Code Online (Sandbox Code Playgroud)
然后适当地命名您的类:
class App.Example
#...
Run Code Online (Sandbox Code Playgroud)
然后通过App命名空间引用所有内容.
And*_*w E 12
我知道这是一个旧线程,但是如果其他人发现它有用,请用"@"声明你的类,它可以被.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"
Run Code Online (Sandbox Code Playgroud)
编译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>
Run Code Online (Sandbox Code Playgroud)