将@分配给单独的对象以便于命名空间

时间:2013-08-30 13:14:10

标签: javascript namespaces coffeescript

在coffeescript中,您可以通过在@符号前加上定义,将对象或类分配给全局命名空间。

e.g。

class @Dog #This is now available via window.Dog due to the @
   constructor : () ->

但有没有将@符号分配给另一个对象,而不是窗口?

当我尝试@ = {}时,我得到error: unexpected =

这将允许您始终将对象定义为命名空间,但是要改变您对以后命名空间的看法。它允许您根据具体情况避免导出。您可以在测试时将@设置为global,然后在部署时将其设置为备用命名空间。

如果有更好的方法,或者实现类似目标的替代方法也会很棒!

3 个答案:

答案 0 :(得分:1)

无法this分配内容,this是范围变量。

猜测你可以创建一些函数来设置命名空间:

@scope = do ( -> return @ ) #change `@` at the end to your namespace

然后你会这样做:

class @scope.Dog
   constructor: () ->
      ...

解析为:

this.scope = (function() {
  return this;
})();

this.scope.Dog = (function() {

  function Dog() {
      ...
  }

  return Dog;

})();

答案 1 :(得分:0)

您无法在顶级更改this,但可以call a function使用不同的this范围:

(->
  class @Dog
    talk: -> console.log 'woof!'
  class @Cat
    talk: -> console.log 'meow'
).call animals = {}

# Now the animals "namespace" has a Cat and a Dog properties.
(new scope.Cat).talk()

这个例子没有多大意义,因为它可以写成animals = {}; class animals.Cat并且不需要额外的嵌套级别,但是如果你想要动态更改this有一点,很高兴知道Function#call:)

的存在

答案 2 :(得分:0)

使用@作为 window 对象的引用可能会产生误导,并可能导致错误(当上下文发生变化时)。更好的是声明一些自定义命名空间。

您在正在加载的第一个脚本中添加一行:

window.myns ?= {}

...后来使用它代替@ like:

class myns.Dog

为了安全起见,您可以在每个文件的顶部添加名称空间声明行,您将在其中进行相关操作。但这不是强制性的。只需确保脚本按正确顺序加载。