0

So I'm looking at some code from "Eloquent Javascript" and it says that to cause inheritance you might write a function like:

function clone(object) {
    function OneShotConstructor() {}
    OneShotConstructor.prototype = object;
    return new OneShotConstructor();
}

and would call it like so, if a class Terrarium was already defined:

function LifeLikeTerrarium(plan) {
    Terrarium.call(this, plan);
}
LifeLikeTerrarium.prototype = clone(Terrarium.prototype);
LifeLikeTerrarium.prototype.constructor;

So my question is why we need to create the OneShotConstructor in order to copy its prototype. Why couldn't we just have written something like:

LifeLikeTerrarium.prototype = new Terrarium();

Would this create any problems, is it improper javascript?

jrbalsano
  • 774
  • 4
  • 17
  • I also found a similar interpreatation here: http://pivotallabs.com/users/pjaros/blog/articles/1368-javascript-constructors-prototypes-and-the-new-keyword under "And for my last trick." Here the method is called create, and it seems the reason is so we don't need to specify parameters to the constructor, but why does clone/create get us around the problem of needing to give the constructor parameters? – jrbalsano Mar 28 '12 at 04:21

2 Answers2

2

See Crockford's prototypal inheritance:

http://javascript.crockford.com/prototypal.html

beyond setting the prototype, you need to call the new keyword which sets the object's internal [[prototype]] property to be the constructor function's external prototype. It then executes the constructor function, using the new object whenever this is mentioned..

A nice explanation is here:

What is the 'new' keyword in JavaScript?

and here:

http://joost.zeekat.nl/constructors-considered-mildly-confusing.html

Community
  • 1
  • 1
bryanmac
  • 37,512
  • 9
  • 85
  • 95
  • Thanks. Those links helped a lot! I don't know if its my Java OOP drilled into my head or just the nature of prototypal programming that was really throwing me for a loop but it took a while to finally piece together all of it. – jrbalsano Mar 28 '12 at 05:11
1

So my question is why we need to create the OneShotConstructor in order to copy its prototype. Why couldn't we just have written something like:

LifeLikeTerrarium.prototype = new Terrarium();

Would this create any problems, is it improper javascript?

Because calling new Terrarium() will, besides cloning the object, call it's constructor which has unknown consequences. If you do it the roundabout way, you clone the object without calling the constructor.

Kernel James
  • 2,830
  • 18
  • 17