咖啡脚本类中对象内部"this"


在我的

类中,我有对象(只是为了方便起见放置所有相关函数),所以我称它们为"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根本不是一个真正的方法。

有几种方法可以解决这个问题。

  1. 完全摆脱helpers并使用=>

    class Test
        constructor: -> @vir = ""
        func1: => @vir = "a"
    t = new Test
    f = t.func1
    f() # @ is what you expect it to be
    
  2. 创建新
  3. 实例时,绑定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()
    
  4. 将函数提供给事件处理系统时绑定函数:

    class Test
        constructor: -> @vir = ""
        helpers:
            func1: -> @vir = "a"
    t = new Test
    whatever.on('some-event', t.helpers.func1.bind(t))
    
  5. 告诉事件处理系统应该是什么@。某些事件系统允许您指定调用事件处理程序时要使用的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
    

当然还有其他方法可以解决这个问题,但我认为以上是最常见的方法。

最新更新