类中,我有对象(只是为了方便起见放置所有相关函数),所以我称它们为"this"指向当前对象。
例如:
类测试 构造函数: -> @vir = " 助手: 函件 1: -> @vir = "a"(我不能这样做,因为指向对象"func1") 功能2: ->
实际上,我可以将我的根对象(或该全局变量)作为参数传递,但我想知道咖啡脚本的方式,也许还有另一种方式作为事件的"=>"?
CoffeeScript 类不是这样工作的。当你说这样的话时:
class C
helpers:
f: -> console.log(@)
helpers
将只是一个附着在C
原型上的物体。不会有任何对 C 的特殊附件,因此:
c = new C
c.helpers.f()
与以下相同:
c = new C
h = c.helpers
h.f()
两者都会在控制台中转储helpers
自身。
您不能在这里使用=>
来帮助任何事情,因为同样,helpers
只是一个与C
没有特殊联系的对象。因此,如果您尝试此操作:
class C
helpers:
f: => console.log(@)
c = new C
c.helpers.f()
您将在控制台中获取C
本身。发生这种情况是因为f
这里只是一个附加到C
原型的对象内部的函数,f
根本不是一个真正的方法。
有几种方法可以解决这个问题。
完全摆脱
helpers
并使用=>
:class Test constructor: -> @vir = "" func1: => @vir = "a" t = new Test f = t.func1 f() # @ is what you expect it to be
创建新实例时,绑定
helpers
中的所有函数:class Test constructor: -> @vir = "" helpers = { } helpers[name] = f.bind(@) for name, f of @helpers @helpers = helpers # Be careful not to mess up the prototype helpers: func1: -> @vir = "a" t = new Test f = t.helpers.func1 f()
将函数提供给事件处理系统时绑定函数:
class Test constructor: -> @vir = "" helpers: func1: -> @vir = "a" t = new Test whatever.on('some-event', t.helpers.func1.bind(t))
告诉事件处理系统应该是什么
@
。某些事件系统允许您指定调用事件处理程序时要使用的this
,我不知道管理事件的内容,因此这可能适用,也可能不适用。class Test constructor: -> @vir = "" helpers: func1: -> @vir = "a" t = new Test whatever.on('some-event', t.helpers.func1, t) # Assuming your event system understands a "context" argument
当然还有其他方法可以解决这个问题,但我认为以上是最常见的方法。