繁体   English   中英

Coffeescript:从同一对象中的函数调用数组函数

[英]Coffeescript: Calling array functions from a function in the same object

我正在尝试为Atom文本编辑器编写一个程序包,在主类(init.coffee)中,我的module.exports内部有一个数组:

servers: []

我想从module.exports另一部分中的函数访问此数组,但是遇到了麻烦。

功能:

stas: () ->
    dir = getFilePath()
    d = fs.statSync dir
    if !d.isDirectory()
        dirError dir
    else
        s = new Server dir
        s.init()
        @servers.push s
    return

我不断收到此错误:

Uncaught TypeError: this.servers.push is not a function

我这样调用该函数:

@events.add atom.commands.add ".tree-view", {
  'atom-together:startServer': @stas
  'atom-together:startClient': @stac
  'atom-together:stopServer': @stos
  'atom-together:stopClient': @stoc
}

在coffeescript中调用此数组的正确方法是什么?

JavaScript / CoffeeScript函数中的this (AKA @ )的值通常取决于调用方式,而不取决于定义位置。 另外, @stas只是对stas函数的引用, this将是调用该函数时调用者希望它成为的任何对象。

如果在回调函数中需要特定的@ (又称this ),则可以将其定义为绑定函数

stas: () => # Note the => instead of ->
  #...

或在将其传递给事件系统时使用Function.prototype.bind绑定:

@events.add atom.commands.add ".tree-view", {
  'atom-together:startServer': @stas.bind(@)
  #...
}

另外,如果您要定义servers: []在类级别是这样的:

class C
  servers: []

那么您将在一个类的所有实例之间共享一个servers阵列,而这可能并不是您想要的。 在类级别定义的事物通过原型在所有实例之间共享。 例如:

class C
  a: [ ]

c1 = new C
c2 = new C
c1.a.push 11
console.log c1.a, c2.a

会在控制台中放置两个[11] ,因为c1.ac2.a是同一数组。 通常,最好在constructor定义可变值,以避免这种共享(除非您特别希望发生这种情况)。 这个版本:

class C
  constructor: (@a = [ ]) ->

c1 = new C
c2 = new C
c1.a.push 11
console.log c1.a, c2.a

会在控制台中为您提供[11][] ,通常这就是您要寻找的行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM