【问题标题】:Coffeescript class losing functionsCoffeescript 类丢失函数
【发布时间】:2011-09-27 03:22:05
【问题描述】:

我有一个无法从中调用函数的 CoffeeScript。但是,如果我声明它的一个实例并向该实例添加函数,它就可以工作。我错过了什么?

函数没有被调用:

  class testClass 
    username: 'Fred'

    this.testFunction = ()->
      alert 'test'

  test = new testClass

  test.testFunction()   

功能工作:

  class testClass 
    username: 'Fred'

  test = new testClass

  test.testFunction = ()->
    alert 'test'

  test.testFunction()

【问题讨论】:

    标签: class function coffeescript


    【解决方案1】:

    class 主体中,this 指向类本身,而不是其原型。你想要的是

    class testClass 
      username: 'Fred'
    
      testFunction: ->
        alert 'test'
    

    另一方面,写入this.testFunction = 会创建testClass.testFunction

    【讨论】:

      【解决方案2】:

      试试

       class testClass 
          username: 'Fred'
          testFunction: ()->
            alert 'test'
      
        test = new testClass
      
        test.testFunction()   
      

      Coffeescript 将类作为第一级概念; this.testfunction = 是错误的。您应该将其定义为函数类型的字段。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-17
        • 1970-01-01
        • 2013-11-17
        • 1970-01-01
        • 2013-07-15
        • 2015-01-01
        相关资源
        最近更新 更多