Search code examples
javascriptinheritanceprototypal-inheritance

Prototypal inheritance with function constructors


If we assume that javascript uses two ways of building proper inheritance, with function constructors and keyword 'new', and pure prototypal inheritance with Object.create:

how can I make prototype chain by using exclusively function constructor method:

function Original() {
    this.name = 'John';
}
var copyOne = new Original();
copyOne.lastname = 'Doe';

var copyTwo = ?

Now, how can I build 'copyTwo' object that inherits both items from 'copyOne' and 'Original'. But items from copyOne object should be inside prototype of copyTwo, so that it is lighter on memory usage (as inherited objects all point to only one prototype instance, and don't have a copy of an item). I go to Chrome debugger and enter console.log(copyTwo) to see where those items are located in copyTwo object.

I am aware that this prototype chain can be built by using Object.create way, but I don't know how to mimic it with function constructors and 'new'.

Let's suppose that I don't want to use pure prototypal instance with using Object.create for building copyTwo.

Is there a way? Thanks.


Solution

  • function Copy(){}
    Copy.prototype = new Original;
    Copy.prototype.lastname="doe";
    
    var copyTwo = new Copy;
    

    However, there are not two kinds of inheritance , js has prototypal inheritance and thats it.

    And if you want light weight memory usage, dont set static props in the constructor but the prototype:

    function Original() {   }
    
    Original.prototype = { name:'John'};