Jon Wells
Jon Wells

Reputation: 4259

Javascript Prototype Class inheritance

I have done a lot of reading. I have written a lot of dummy code. I am still as confused as I when I set out to once and for all conquer JavaScript inheritance. Maybe more so.

I am quite in admiration of Backbone.js and I liked its use of collections. So I read the source and felt inspired. But I keep tripping up over inheritance vs extending an object.

Here is, as best as I can deduce a Javascript class with inheritance, for this use purpose I cannot see the benfit in using extend:

    function Collection(){
        this._models = [];
    }

    Collection.prototype = {

        models: function() {
            return this._models;
        },

        fetch: function() { 
            console.log("TODO Override fetch method"); 
        },

        add: function(model){
            this._models.push(model);
            $(this).triggerHandler("add", model);
        },
    }

    function Employees(){}

    Employees.prototype = new Collection();

    Employees.prototype.fetch = function(){
        this._models = [new Person("Ron", "male"), new Person("Stevie", "female"),  new Person("David Blunkett", "female")];
    }

It feels a little strange accessing the super classes(Collection) _models property directly in Employees but it works. Is there anything wrong with this approach? Any gottchas or caveats? I don't want to build an application off of this to find out its a bit... naff.

Edit its probably worth noting a Person is a Model too...

function Model(){}

Model.prototype = {
    get: function(attr){
        return this.attr;   
    },
    set: function(attr, value){
        return this[attr] = value;
    }
}

function Person(name, gender){
    this.name = name;
    this.gender = gender;
}

Person.prototype = new Model();

Upvotes: 1

Views: 222

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 146014

Your approach of making a new instance of the parent class and assigning that as the prototype of the child class is what Douglas Crockford calls the "Pseudoclassical" approach to inheritance in JavaScript. Check out this in-depth video where he covers in detail pseudoclassical, prototypal, and parasitic inheritance approaches as well as several variants. (Pseudoclassical is around 12 minutes in).

Your approach works fine with the one (potentially large) limitation in that you cannot share constructor code in this pattern (at least not without some extra fanciness). So if you do:

var e = new Employees();
console.log(e.constructor);

You will see the Collection function instead of the more intuitive Employees function. Again, watch that video, it really covers this entire topic very clearly.

Upvotes: 1

Related Questions