2012-10-01 31 views
1

我有,我已經定義我的課的外部文件:CoffeeScript:爲什麼我的課程沒有在沒有窗口前綴的情況下工作?

class MyClass 
    constructor: -> 
    alert 'hello' 

當CoffeeScript的被編譯成JavaScript,它與一個封閉包裝它。所以,當我嘗試使用它在一些JavaScript:

$(function(){ 
    var ob = new MyClass(); 
}); 

我得到的錯誤:

Uncaught ReferenceError: MyClass is not defined 

但如果我前面加上窗口類名,它的工作:

class window.MyClass 
    constructor: -> 
    alert 'hello' 

如何定義我的類而不用窗口作前綴?

+0

我經常做'self.MyClass = class MyClass'並想知道是否有更好的方法。順便說一句,我使用'self'因爲它更便於攜帶,網絡工作者沒有'window'對象。 – clockworkgeek

回答

1

您可以使用--bare編譯CoffeeScript,但通常不建議這樣做,因爲您可能會污染全局名稱空間。

我的建議是對類附加到window對象,就像你的第二個例子,甚至更好,使用此命名空間功能從CoffeeScript的文檔到你的類連接到連接到window

namespace = (target, name, block) -> 
    [target, name, block] = [(if typeof exports isnt 'undefined' then exports else window), arguments...] if arguments.length < 3 
    top = target 
    target = target[item] or= {} for item in name.split '.' 
    block target, top 

# Usage: 
# 
namespace 'Hello.World', (exports) -> 
    # `exports` is where you attach namespace members 
    exports.hi = -> console.log 'Hi World!' 

namespace 'Say.Hello', (exports, top) -> 
    # `top` is a reference to the main namespace 
    exports.fn = -> top.Hello.World.hi() 

Say.Hello.fn() # prints 'Hi World!' 
一個全局對象

來源:CoffeeScript FAQ

相關問題