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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With