我在Coffeescript FAQ上找到了这个片段,用于创建简单的命名空间.
# Code:
#
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!'
Run Code Online (Sandbox Code Playgroud)
这一切都很好,但我在使用class关键字时遇到了很多麻烦.这样......
namespace 'Project.Something', (exports) ->
exports.something = -> class something
// .. code here
exports.somethingElse = class somethingElse extends something
Run Code Online (Sandbox Code Playgroud)
任何人都可以对可以实现此目的的语法有所了解吗?
Chr*_*gio 24
更好的是,类语法允许名称实际上是成员的形式,所以你实际上可以这样做:
namespace 'Secrets', (exports) ->
class exports.Hello
constructor: ->
@message = "Secret Hello!"
a = new Secrets.Hello
console.log a.message
Run Code Online (Sandbox Code Playgroud)
完整的小提琴:http://jsfiddle.net/7Efgd/1/
San*_*dro 19
诀窍是首先创建类
class MyFirstClass
myFunc: () ->
console.log 'works'
class MySecondClass
constructor: (@options = {}) ->
myFunc: () ->
console.log 'works too'
console.log @options
Run Code Online (Sandbox Code Playgroud)
然后在文件末尾附近的某处导出所有需要暴露的类.
namespace "Project.Something", (exports) ->
exports.MyFirstClass = MyFirstClass
exports.MySecondClass = MySecondClass
Run Code Online (Sandbox Code Playgroud)
稍后您可以使用这样的类:
var firstClass = new Project.Something.MyFirstClass()
firstClass.myFunc()
var secondClass = new Project.Something.MySecondClass
someVar: 'Hello World!'
secondClass.myFunc()
Run Code Online (Sandbox Code Playgroud)