Search code examples
javascriptprototype

Different ways of inheriting


I've seen that in many cases inheritance in js can be implemented like so

function Organism(age) {
    this.age = age;
}

Organism.prototype.growOlder = function(){ this.age = this.age + 1}
var org = new Organism("1000");

function Human(name,age){
     Organism.call(this,age); //this sets up the properties on the human object
     this.name = name;
}

Human.prototype = Object.create(Organism)
Human.prototype.constructor = Human; //sets the constructor
Human.prototype.run = function(){ console.log(this.name + "run")}

My question is if someone can explain in detail why Object.create(Organism) is necessary and simply doing this

Human.prototype = Organism.prototype

is not enough.Respectively the prototype chain looks like

without object.create : Human.__proto__ -> Organism __proto__-> Object

with object.create: Human.__proto__-> IntermediateObject.__proto__ -> Organism.__proto__-> Object

Thank you for your time.

EDIT: I am aware of the es6 class and inherits syntactic sugar. Im just curious how things work on the lower levels though.


Solution

  • My question is if someone can explain in detail why Object.create(Organism) is necessary and simply doing this Human.prototype = Organism.prototype is not enough.

    You can totally do this, and it will even work.

    However there is subtle problem. If you assign Organism.prototype directly it will cause a nasty side effect when Organism will inherit all the methods you create on Human.prototype. Not what you want.

    For example if you do Human.prototype = Organism.prototype then org will have run, however it should probably not have methods of Human.