开发者

Calling a method from the constructor in Coffeescript

开发者 https://www.devze.com 2023-03-26 21:17 出处:网络
Is it possibl开发者_如何转开发e to call a method from the constructor in Coffeescript? e.g. class Animal

Is it possibl开发者_如何转开发e to call a method from the constructor in Coffeescript?

e.g.

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"

This is generating the following error message "ReferenceError: move is not defined"


It is possible. However, to refer to the method you must use @move() or this.move(), the name move() itself is not enough.


Gotcha Alert: if you find that @ or this does NOT refer to the new instance in a constructor, check you remembered to use the NEW keyword:

instance = new Class()

NOT:

instance = Class()

This caught me out and was really frustrating. Hope this helps someone else!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号