简体   繁体   中英

Copying prototypes requires a new object? javascript

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM