Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different ways of inheriting [duplicate]

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.

like image 712
Return-1 Avatar asked Mar 13 '18 13:03

Return-1


People also ask

What is a replicated inheritance?

Repeated inheritance occurs whenever (as a result of multiple inheritance) two or more of the ancestors of a class D have a common parent A. D is then called a repeated descendant of A, and A a repeated ancestor of D.

Can you name some alternatives to inheritance?

Delegation can be an alternative to inheritance. Delegation means that you use an object of another class as an instance variable, and forward messages to the instance.


1 Answers

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.

like image 114
dfsq Avatar answered Oct 06 '22 01:10

dfsq