【问题标题】:Coffeescript - How to call method of parent classCoffeescript - 如何调用父类的方法
【发布时间】:2013-05-17 01:03:11
【问题描述】:
class Foo 
  foo: () ->
    console.log("foo method Called")

class Bar extends Foo
  constructor: () ->
    console.log("Bar created")

  bar: () ->
    console.log("bar method called")
    foo

b = new Bar
b.bar()

结果:
酒吧创建
调用 bar 方法
ReferenceError: foo 未定义

如何调用 foo 方法?

【问题讨论】:

  • 你用括号试过了吗?

标签: coffeescript


【解决方案1】:

这里有两个问题。

首先,您需要致电this.foo(或@foo)。

其次,在 CoffeScript 中,函数定义中提到的最后一个变量被返回,而不是执行。因此,如果您想调用该函数,您的代码需要如下所示:

bar: () ->
    console.log("bar method called")
    this.foo() // or @foo()

否则,如果没有(),它将返回函数而不是调用它。请注意,这也将编译为return this.foo(),因此如果您不想返回任何内容,请在最后一行添加一个空白return

【讨论】:

  • 正确,但从风格上讲,大多数 CoffeeScripter 会写 @foo() 来调用实例方法。
  • @AlexWayne 每个人都有自己的 ;)
  • 谢谢!我认为这很简单:)
  • @Michael:我很确定如果没有括号,函数不会被调用(执行),您将return foo;return foo(); 进行比较(其中typeof foo === 'function'
【解决方案2】:

使用@foo()。在类中声明的functions 被添加到类的prototype 中。看看代码here产生的javascript

要调用直接添加到函数原型的函数,您需要this

【讨论】:

    猜你喜欢
    • 2020-01-14
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2011-01-03
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多