mateusmaso
mateusmaso

Reputation: 8453

How to know when a Class is inherited with Coffeescript extends?

I would like to have the same approach that Ruby provides with a static method 'inherited' as you see inside their documentation for modules manipulation purpose:

class Foo
  @inherited: (subclass) ->
    console.log('hey hou')

class Hey extends Foo

class Hou extends Foo

Outputs:

=> hey hou
=> hey hou

How can I accomplish that with Coffeescript 'extends'? I mean, if I were using Backbone.js 'extend' method I could overrite it.. but Coffeescript compiles it and it's impossible to do that.

Any thoughts?

Upvotes: 2

Views: 231

Answers (2)

David Bonnet
David Bonnet

Reputation: 1218

Alex Wayne's answer is perfectly legit and the right way to do.

However, in case you really need it (e.g., for debugging purposes) without having to make an explicit function call, you can also redefine the __extends function generated by the CoffeeScript compiler at the beginning of each file. Since __extends is a reserved keyword in CoffeeScript, it must be redefined in plain JavaScript and embedded in the CoffeeScript file with backticks:

`
__extends = (function (extend) {
    return function (child, parent) {
        // Do actual heritage
        var result = extend(child, parent);
        // Do something with child or parent
        if (parent.inherited instanceof Function) parent.inherited(child);
        // Return the result as in the original '__extends' function
        return result;
    }
})(__extends);
`

Upvotes: 2

Alex Wayne
Alex Wayne

Reputation: 187044

Nope.

It used to have this, it was removed. Some want it back in, but there is funkiness about how it would need to work.

Some reference about this from the source:

The suggested workaround relies on an explicit call from the child class.

class A extends B

  # child class calls extended hook of parent class explicitly.
  B.extended(this)

  classBody: ->
  methods: ->
  goHere: ->

Upvotes: 1

Related Questions