Skip to content
Advertisement

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 :)!

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement