相關:Classes within Coffeescript 'Namespace'如何在Node中使用coffeescript的命名空間代碼?
好的,所以在閱讀該文章後,我抓住了命名空間函數並將其放在它自己的文件中。
namespace.coffee
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
console.log "created namespace "+ name
root = exports ? window
root.namespace = namespace
,然後在REPL:
> namespace = require('./assets/js/namespace.js').namespace
[Function]
如果我的toString()它,它的正確。
好了,現在我想用它:ns.coffee
(由桑德羅的答案)
namespace = require('./namespace.js').namespace
class MyFirstClass
myFunc:() ->
console.log 'works'
class MySecondClass
constructor: (@options = {}) ->
myFunc:() ->
console.log 'works too'
console.log @options
namespace "Project.Something", (exports) ->
exports.MyFirstClass = MyFirstClass
exports.MySecondClass = MySecondClass
console.log 'done with exports'
然後我在REPL運行:
NS =需要(」 ./資產/ JS /ns.js')#編譯ns.coffee
其中出口完成
創建命名空間Project.Something
{}
它似乎並沒有被工作:
> ns.MyFirstClass
undefined
> ns.MySecondClass
undefined
> ns.Project.Something.MySecondClass
TypeError: Cannot read property 'Something' of undefined
上午我做錯了什麼嗎?
似乎如果是這樣的話,我不會看到來自命名空間文件的控制檯日誌消息,但我這樣做:「創建名稱空間Project.Something」 – jcollum
@jcollum爲什麼不呢? 'namespace'的參數可以很好地傳遞。 –
當然,該代碼正在運行,但它顯然不創建名稱空間,或者我錯誤地調用它。 – jcollum