coffeescript类在主javascript中不可访问 [英] coffeescript Class not accessible in main javascript

查看:88
本文介绍了coffeescript类在主javascript中不可访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以coffeescript写的类,例如

I have a class written in coffeescript, e.g.,

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

我有一个单独的文件类Example.coffee

and I have this class as a separate file, Example.coffee

现在我想能够在我的主要javascript文件中实例化:

Now I want to be able to instantiate in my main javascript file like so:

d = new Example
d.render()

即使当它作为脚本包括在页面上时也是未定义的,例如

but the class is undefined even when it is included as a script on the page, like

<script src="Example.js></script>
<script src="main.js"></script>



How do you make the class publicly available to the main file?

推荐答案

您可以声明您的类可以全局访问(至少对浏览器),通过声明它在窗口命名空间:

You can declare your class to be globally accessible (at least for browsers) by declaring it to be in the window namespace:

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

示例直接放入窗口。您也可以在大多数情况下说 class @Example

That will put Example straight into window. You can also say class @Example in most cases.

默认情况下,CoffeeScript将每个文件包裹在(function(){...})() wrapper以防止命名空间污染。您可以通过在编译CoffeeScript时提供 -b 来防止出现这种情况:

By default, CoffeeScript wraps each file in a (function() { ... })() wrapper to prevent namespace pollution. You can prevent this by supplying -b when compiling your CoffeeScript:


-b,--bare

编译JavaScript顶层函数安全包装器。

-b, --bare
Compile the JavaScript without the top-level function safety wrapper.

但这可能不是一个选项(或者它可能是一个丑陋的)。通常的方法是在加载类之前在某个地方声明一个特定于应用程序的命名空间:

but that might not be an option for you (or it might be an ugly one). The usual approach is to declare an application specific namespace somewhere before your classes are loaded:

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

,然后为您的类命名空间:

and then namespace your classes appropriately:

class App.Example
    #...

然后通过 App 命名空间引用所有内容。

Then refer to everything through the App namespace.

这篇关于coffeescript类在主javascript中不可访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆