Coffeescript'Namespace'中的类

时间:2012-01-04 17:07:04

标签: coffeescript

我在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!'

这一切都很好,但我在使用class关键字时遇到了很多麻烦。这样......

namespace 'Project.Something', (exports) ->
   exports.something = -> class something
    // .. code here
   exports.somethingElse = class somethingElse extends something

任何人都可以对可以实现此目的的语法有所了解吗?

3 个答案:

答案 0 :(得分:24)

更好的是,类语法允许名称实际上是成员的形式,所以你实际上可以这样做:

namespace 'Secrets', (exports) ->
  class exports.Hello
    constructor: ->
      @message = "Secret Hello!"

a = new Secrets.Hello
console.log a.message

这里完整的小提琴:http://jsfiddle.net/7Efgd/1/

答案 1 :(得分:19)

诀窍是首先创建类

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

稍后你可以这样使用这些类:

var firstClass = new Project.Something.MyFirstClass()
firstClass.myFunc()

var secondClass = new Project.Something.MySecondClass 
  someVar: 'Hello World!'

secondClass.myFunc()

答案 2 :(得分:1)

如何使用这样的东西?

module =
    Hello: class Hello extends Backbone.Model
        constructor: ->
            @message = 'Hello'

    Hello2: class Hello2 extends Backbone.View
        constructor: ->
            @message = 'Hello2'