culturalanomoly
culturalanomoly

Reputation: 1301

JavaScript Prototype Assignment

What is the recommended approach/pattern for assigning an object's prototype? Assigning a reference to an already instantiated instance of 'super' function or initializing a new instance of 'super' for every 'sub' function? If, multiple approaches are commonplace; what are the pros/cons of each?

function SuperFoo(){ };
function Foo() {};
function Fooy() {};
function Fooimus() {};
function Foolacious() {};


/* Option 1: */ 
var proto = new SuperFoo();
Foo.prototype = proto;
Fooy.prototype = proto;
Fooimus.prototype = proto;
Foolacious.prototype = proto;


/* Option 2: */ 
Foo.prototype = new SuperFoo();
Fooy.prototype = new SuperFoo();
Fooimus.prototype = new SuperFoo();
Foolacious.prototype = new SuperFoo();

Upvotes: 2

Views: 1235

Answers (1)

The Spooniest
The Spooniest

Reputation: 2873

Multiple approaches are commonplace. But generally, what people actually want to do isn't actually covered by any of the solutions you list.

What you generally want from a subclass is a constructor whose prototype property is an object, which itself inherits from the prototype property of the superclass constructor. It's also a good idea to make sure that the prototype constructors match up properly: the prototype should have a constructor property that points back to its own class constructor. The result can look like this:

function SuperFoo() {};  // assuming that some prototype functions are already defined.

function Foo() {};
Foo.prototype = Object.create(SuperFoo.prototype);
Foo.prototype.constructor = Foo;

My usual solution nowadays is to wrap this rigamarole up into a function, like so:

Object.subclass = function (sub, sup) {
    sub.prototype = Object.create(sup.prototype);
    sub.prototype.constructor = sub;
};

function SuperFoo() {};  // assuming that some prototype functions are already defined.

function Foo() {};
Object.subclass(Foo, SuperFoo);

function Fooy() {};
Object.subclass(Fooy, SuperFoo);

function Fooimus() {};
Object.subclass(Fooimus, SuperFoo);    

function Foolacious() {};
Object.subclass(Fooalicious, SuperFoo);

Upvotes: 4

Related Questions