SpaceFace
SpaceFace

Reputation: 1552

Copy prototype for inheritance?

I was playing around with JavaScript in particular simulating object oriented programming with classes and whatnot.

I knew about this way of achieving inheritance

MyClass.prototype = new AnotherClass();

But I wasn't satisfied, I didn't like how I needed to call the constructor of AnotherClass. So I was playing around and I came up with something that seemed to work and basically want a second opinion.

function clone (obj)
{
    function CloneFactory () {}
    CloneFactory.prototype = obj;

    return new CloneFactory();
}

MyClass.prototype = clone(AnotherClass.prototype);

By cloning the prototype we get a new copy of it and assign that to MyClass's prototype so that changing the inherited properties will not affect the parent's prototype's properties. Like this would MyClass.prototype = AnotherClass.prototype.

I ran stress tests and this is more efficient under certain circumstances, i.e. when there's a lot of code in the parent's constructor, otherwise it's about the same. Another benefit (or at least I find it to be beneficial) is that it allows to some extent information hiding from the subclasses. Any privileged methods and members will NOT be inherited.

Is there some major pitfall that I'm overlooking?

I'm not an expert with JavaScript, actually I'm fairly new to JavaScript, so I'd like to have a second opinion on this because I can't seem to find anything through Google. I don't want to implement bad code :)!

Upvotes: 22

Views: 24612

Answers (2)

Hybrid web dev
Hybrid web dev

Reputation: 340

I ran into this question, as I was looking for a solution to this myself. I think the best solution, is to create the function from a factory function.

let functionFactory = function(){

    let o = function(o, ...args){

    }
    o.prototype.foo = 'bar'

    return o

}

Then, to use it you just do:

let myinstance = new functionFactory;
myinstance.bar = 'bar'

This way you still get the benefits of shared prototype etc, but can create a new copy that you can then override per instance, without other instances stomping on your changes.

Upvotes: 1

Kevin Ennis
Kevin Ennis

Reputation: 14466

This is almost exactly what Object.create does. The function you've written is a pretty standard "polyfill" for that method.

This is a really common way of abstracting object creation in a way that more closely reflects "true" prototypal inheritance. Definitely a safe way to do things.

Oh, and here's a link to the MDN entry for Object.create, if you're interested: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/create/

You'll notice at the bottom that they actually include the polyfill, which is pretty much identical to your code, save for some safety checks and variable names.

Upvotes: 26

Related Questions