Alex Rivera | Logout

Prototypal Inheritance best practices?

Asked 2012-01-15T22:59:35.540
19

I'm just getting into JavaScript and I'm trying to wrap my head around prototypal inheritance. It appears that there's multiple ways to achieve the same effect, so I wanted to see if there is any best practices or reasons to do things one way over the other. Here's what I'm talking about:

// Method 1
function Rabbit() {
    this.name = "Hoppy";

    this.hop = function() {
        console.log("I am hopping!");
    }
}

// Method 2
function Rabbit() {}

Rabbit.prototype = {
    name: "Hoppy",

    hop: function() {
        console.log("I am hopping!");
    }
}

// Method 3
function Rabbit() {
    this.name = "Hoppy";
}

Rabbit.prototype.hop = function() {
    console.log("I am hopping!");
}

// Testing code (each method tested with others commented out)
var rabbit = new Rabbit();
console.log("rabbit.name = " + rabbit.name);        
rabbit.hop();

All of these appear to have the same effect individually (unless I'm missing something). So is one method preferred over the other? How do you do it?

Edit
Report

1 Answer

1
// option 4
var Rabbit {
    constructor: function () {
        this.name = "Hoppy";
        return this;
    },

    hop: function() {
        console.log("I am hopping!");
    }
};

var rabbit = Object.create(Rabbit).constructor();
console.log("rabbit.name = " + rabbit.name);        
rabbit.hop();

When doing prototypical OO using new and constructor functions is completely optional.

As has already been noted, if you can share something through the prototype do so. Prototypes are more efficient memory wise and they are cheaper in terms of instantiation time.

However a perfectly valid alternative would be

function Rabbit() {
    // for some value of extend https://gist.github.com/1441105
    var r = extend({}, Rabbit);
    r.name = "Hoppy";
    return r;
}

Here your extending "instances" with the properties of the "prototype". The only advantage real prototypical OO has is that it's a live link, meaning that changes to the prototype reflect to all instances.

answered 2012-01-15T23:15:06.670

Your Answer