CoffeeScript的类中主要的JavaScript无法访问(coffeescript Clas

2019-09-16 11:25发布

我已经写在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>

如何做才能让你的类公开可用的主文件?

Answer 1:

你可以声明你的类全局访问(至少对于浏览器)通过声明它是在window命名空间:

class window.Example
  constructor: ->
    $.each [1, 2, 3], (key, value) =>
      @test = value
    return @test
  render: ->
    alert @test

这将使Example直入window 。 你也可以说class @Example在大多数情况下。

默认情况下,CoffeeScript的包装中的每个文件(function() { ... })()的包装,以防止命名空间污染 您可以通过提供防止这种-b编译你的CoffeeScript时:

-b, --bare
编译JavaScript的没有顶级功能安全包装。

但是这可能不是一个选择(或者它可能是一个丑陋的一个)。 通常的做法是在某处声明应用特定的命名空间的类被加载之前:

// Probably in a <script> in your top-level HTML...
App = { };

然后适当地命名空间的类:

class App.Example
    #...

然后通过指一切App的命名空间。



Answer 2:

我知道这是一个古老的线程,但如果任何人发现它是有用的,声明你的类以“@”,这将是访问.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>


Answer 3:

创建一个全局变量

window.Example = Example



文章来源: coffeescript Class not accessible in main javascript