我正在尝试为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
将成为调用该函数时调用者希望它成为的对象。
如果在回调函数中需要特定的@
(AKA 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]
s放入控制台,因为c1.a
和c2.a
是相同的数组。通常,最好在您的变量中定义可变值,constructor
以避免这种共享(除非您特别希望发生这种情况);这个版本:
class C
constructor: (@a = [ ]) ->
c1 = new C
c2 = new C
c1.a.push 11
console.log c1.a, c2.a
会在控制台中为您提供[11]
,[]
通常这就是您要寻找的行为。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句