从 Coffeescript 的构造函数中调用方法
是否可以从 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:未定义移动”
Is it possible 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"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是可能的。但是,要引用该方法,您必须使用
@move()
或this.move()
,名称move()
本身不是足够的。It is possible. However, to refer to the method you must use
@move()
orthis.move()
, the namemove()
itself is not enough.陷阱警报:如果您发现 @ 或 this 并不引用构造函数中的新实例,请检查您是否记得使用 NEW 关键字:
NOT:
这让我感到困惑,真的很令人沮丧。希望这对其他人有帮助!
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:
NOT:
This caught me out and was really frustrating. Hope this helps someone else!