2

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();
2
  • Crockford's write-up on this topic should be helpful to you: crockford.com/javascript/inheritance.html Commented May 8, 2014 at 17:33
  • It depends on what you want to achieve. In this state, the question is too broad. Commented May 8, 2014 at 17:36

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.