Class 使用不同文件的Coffeescript命名空间

Class 使用不同文件的Coffeescript命名空间,class,coffeescript,namespaces,Class,Coffeescript,Namespaces,考虑以下类别: class A constructor: -> @nestedA = new NestedA() class NestedA constructor: -> @NestedA = NestedA @A = A class B constructor: -> @nestedB = new NestedB() class NestedB constructor: -> @NestedB = N

考虑以下类别:

class A
  constructor: ->
    @nestedA = new NestedA()

  class NestedA
    constructor: ->

  @NestedA = NestedA

@A = A

class B
  constructor: ->
    @nestedB = new NestedB()

  class NestedB
    constructor: ->

  @NestedB = NestedB

@B = B

这样,类
A
B
可以在全局名称空间中使用,而
NestedA
NestedB
只能分别通过
A
B
名称空间使用。我喜欢这种方法,但这会导致单独的coffeescript文件变得相当大。因此,我想知道是否有办法将类(NestedA和NestedB)分离到单独的coffeescript文件中,并且仍然保持名称空间?

您可以使用RequireJS将NestedA.coffee作为依赖项加载到a.coffee中(对Bs也可以这样做)。然后使用RequireJS以同样的方式将A.coffee加载到主应用程序中

Class A
  @NestedA = require('cs!NestedA)

这应该是可行的,但如果您还没有使用RequireJS,这可能会有一点架构上的变化。

我会这样做。这种方法与TypeScript非常相似,但该模式同样适用于CoffeeScript

#a.coffee
A = do (A = A ? {})->

    class Foo
        constructor: ->
            @nestedFoo = new NestedFoo()

    class NestedFoo
        constructor ->
        greet: ->
            console.log('Hello World')

    #exports
    A.Foo = Foo
    A.NestedFoo = NestedFoo
    A

#somwhere-else.coffee

foo = new A.Foo()
foo.nestedFoo.greet() #yields 'Hello World'

这种方法的优点是,您可以从任何其他文件向名称空间添加尽可能多的其他功能。

感谢您的建议,我已经考虑过了-我真的很想使用vanilla CoffeeScript,并希望该语言支持类似于此的现成功能。