Hacker News new | ask | show | jobs
by jashkenas 5419 days ago
For the record, the way that CoffeeScript does inheritance and the way that Backbone's "extend" does inheritance is almost literally exactly the same thing.

Both simply create an empty object to serve as the prototype (calling new without actually running your constructor), set up the prototype chain correctly, and stash a reference so that calling `super` is easier later on.

If "Child" and "Parent" are constructor functions (class objects), then the basic pattern is this:

    var ctor = function(){};
    ctor.prototype = Parent.prototype;
    Child.prototype = new ctor;
    Child.prototype.constructor = Child;
    
Fun.
1 comments

This is the way JS devs have been hacking inheritance for a long time. That's irrelevant though, we're not comparing CS to Backbone, we're comparing Batman.js to Backbone.

Backbone handles the messy inheritance code for you. Batman.js relies on CS for that, but a JS dev is going to have to write the inheritance code by hand. I posted the JS equivalent of their example in this thread, it's nasty.

It is indeed nasty ... and for that extra nastiness, above and beyond the inheritance pattern listed above, you get:

* A subclass that inherits the parent's implementation of the constructor function, unless overridden.

* A named function for your class object, without IE scope leaks.

* A way to call super that's as easy as `super()`.

* Inheritance of the parent's own properties (unfortunately via copying).

* ... which enables helpful metaprogramming within class bodies. For example, Batman's own `event` decorator:

    use: @event (times) ->
      return false unless ...