Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am reading kangax's blog on How ECMAScript 5 still does not allow to subclass an array. Here he is using a different approach of subclassing than the normal prototypal construct

BaseClass.prototype = new Superclass();

What he is doing is this :

function clone(obj) {
  function F() { }
  F.prototype = obj;
  return new F();
}

and then set-up inheritance like this:

function Child() { }
Child.prototype = clone(Parent.prototype);

Can someone explain this two part approach of inheritance and what benefits it gives over the simple one liner approach above?

Edit: I understand from the comments that there is now a standard Object.create() that basically solves the same purpose as clone() method but how does this implementation of clone() work ?

share|improve this question
possible duplicate of Benefits of using Object.create for inheritance – Felix Kling 36 mins ago
Because doing new Superclass() may trigger undesired side effects. The clone gives you an object that inherits from the parent, but without having to invoke the constructor function. And FYI, there's now a standard method in JavaScript that does this. It's Object.create() – Crazy Train 36 mins ago
The clone function in your example has the same purpose as Object.create, that's why the answers to the linked question will (hopefully) help you as well. – Felix Kling 36 mins ago
@CrazyTrain What sideeffects can happen if new Superclass() is invoked? – Geek 24 mins ago
@FelixKling PLease see the edit and +1 for your link to the previous answer of yours. It definitely helped. But this question is now more about the implementation of clone(). – Geek 18 mins ago
show 1 more comment

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.