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?
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