Neil
Neil

Reputation: 5239

How can I override a parent method in coffeescript while still being able to call the parent

I have two coffeescript classes something like this. In the base view model I have a method that I want to override in the child that inherits from the base view model.

class exports.BaseViewModel
    constructor: () ->

    someBaseMethod: =>
        console.log "I'm doing the base stuff"

class ChildViewModel extends BaseViewModel
    constructor: () ->

    someBaseMethod: =>
        @doSomethingFirst()
        super @someBaseMethod()

This isn't working as is because the line super @someBaseMethod() calls itself creating an infinite loop.

Is it possible to achieve what I want here?

Upvotes: 16

Views: 6968

Answers (1)

epidemian
epidemian

Reputation: 19219

Yes, call super just like it was a function (it represents a reference to the superclass version of the method you're in):

class ChildViewModel extends BaseViewModel
  constructor: ->

  someBaseMethod: =>
    @doSomethingFirst()
    super()

Upvotes: 31

Related Questions