bmurmistro
bmurmistro

Reputation: 1080

Coffeescript - How to call method of parent class

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()

Results:
Bar created
bar method called
ReferenceError: foo is not defined

How do I call the foo method?

Upvotes: 3

Views: 4417

Answers (2)

MMM
MMM

Reputation: 7310

There are two problems here.

First, you need to call this.foo (or @foo).

Second, in CoffeScript the last variable mentioned in a function definition is returned, not executed. So if you want to call that function your code needs to look like this:

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

Otherwise without the () it will return the function rather than call it. Note that this will also compile to return this.foo(), so if you don't want to return anything, add a blank return on your last line.

Upvotes: 4

kiddorails
kiddorails

Reputation: 13014

Use @foo(). functions declared in class are added to the class's prototype. Have a look at the javascript produced by the code here

To call the functions directly added to a function prototype, you will need this.

Upvotes: 0

Related Questions