Javascript functional inheritance with prototypes

Posted by cdmckay on Stack Overflow See other posts from Stack Overflow or by cdmckay
Published on 2010-03-14T02:26:07Z Indexed on 2010/03/14 2:35 UTC
Read the original article Hit count: 508

In Douglas Crockford's JavaScript: The Good Parts he recommends that we use functional inheritance. Here's an example:

var mammal = function(spec, my) {
    var that = {};
    my = my || {};

    // Protected
    my.clearThroat = function() { 
        return "Ahem";
    };

    that.getName = function() {
        return spec.name;
    };

    that.says = function() {
        return my.clearThroat() + ' ' + spec.saying || '';
    };

    return that;
}

var cat = function(spec, my) {
    var that = {};
    my = my || {};

    spec.saying = spec.saying || 'meow';
    that = mammal(spec, my);

    that.purr = function() { 
        return my.clearThroat() + " purr"; 
    };

    that.getName = function() { 
        return that.says() + ' ' + spec.name + ' ' + that.says();
    };

    return that;
};

var kitty = cat({name: "Fluffy"});

The main issue I have with this is that every time I make a mammal or cat the JavaScript interpreter has to re-compile all the functions in it. That is, you don't get to share the code between instances.

My question is: how do I make this code more efficient? For example, if I was making thousands of cat objects, what is the best way to modify this pattern to take advantage of the prototype object?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about inheritance