【问题标题】:Calling a method from the constructor in Coffeescript从 Coffeescript 中的构造函数调用方法
【发布时间】:2011-10-22 07:14:46
【问题描述】:

是否可以从 Coffeescript 的构造函数中调用方法?
例如

class Animal
  constructor: (@name) ->
    move()

  move: (meters) ->
    alert @name + " moved #{meters}m."

class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5

sam = new Snake "Sammy the Python"

这会生成以下错误消息“ReferenceError: move is not defined”

【问题讨论】:

    标签: coffeescript


    【解决方案1】:

    这是可能的。但是,要引用必须使用@move()this.move()的方法,名称move()本身是不够的。

    【讨论】:

      【解决方案2】:

      注意事项:如果您发现 @ 或 this 不引用构造函数中的新实例,请检查您是否记得使用 NEW 关键字:

      instance = new Class()
      

      不是:

      instance = Class()
      

      这让我大吃一惊,真的很沮丧。希望这对其他人有帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-10
        • 2013-05-08
        • 2016-05-31
        • 1970-01-01
        • 1970-01-01
        • 2015-10-01
        • 2016-02-05
        • 1970-01-01
        相关资源
        最近更新 更多