from Hacker News

The Ways of Javascript Inheritance

by brittonrt on 3/2/13, 12:17 AM with 2 comments

Hey Hacker News! Lets talk about prototypal inheritance in JS!

What's the best way of doing it from a code reusability standpoint?

What's the best way of doing it from a time to create instance standpoint?

What's the best way of doing it from memory footprint standpoint?

Of the ways I've seen and tried, John's method seems the easiest to use: http://ejohn.org/blog/simple-javascript-inheritance/

But I hate that it has to loop through every property every time you extend a prototype.

Most inheritance patterns I've seen need to have the original prototype cloned or instantiated in order extend a new prototype safely. Is there a way to do it that allows all instances at all levels of the inheritance chain to still share the same common methods in memory where they aren't overridden?

Thanks!

  • by ricardobeat on 3/2/13, 3:25 AM

    To cut the story short, there is basically a single way to do "proper" inheritance in javascript, which is Crockford's prototypal inheritance [1]. There are a dozen variations on it, here is one:

        function inherits (child, parent) {
            extend(child, parent)
            function Ctor () { this.constructor = child }
            Ctor.prototype = parent.prototype
            child.prototype = new Ctor()
            child.__super__ = parent.prototype
            return child
        }
    
        function Animal ...
        Animal.prototype.x = ...
    
        function Cat ...
     
        inherits(Cat, Animal)
    
    See Backbone's implementation [2] for another example. This eventually morphed into the standard `Object.create` method [3], supported in IE9+.

    [1] http://javascript.crockford.com/prototypal.html

    [2] http://backbonejs.org/docs/backbone.html#section-186

    [3] https://developer.mozilla.org/en-US/docs/JavaScript/Referenc...

  • by keefe on 3/5/13, 6:27 AM

    I like something like jQuery.extend(true, {}, src)