Heejin avatar

JavaScript - Object.create in `Class`ical Inheritance

heejin

Published: 29 Aug 2017 › Updated: 29 Aug 2017JavaScript - Object.create in `Class`ical Inheritance

JavaScript - Object.create in `Class`ical Inheritance

You've probably seen the Object.create pattern was used to mimic Classical inheritance in JavaScript ES5 such as:

function Animal() {
}

Animal.prototype.say = function() {
  console.log('Say!');
};

function Dog() {
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

You may be curious about why Object.create is used here to make inheritance. So let's figure out why it is needed for proper inheritance.

the following example can also be used to mimic inheritance:

function Animal() {
}

Animal.prototype.say = function() {
  console.log('Say!');
};

function Dog() {
}

Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;

I think you've already noticed this code can cause a side-effect. Copying prototype with new Animal() can cause side-effect, because it will call Animal constructor once. and it's unnecessary action.

So we need to copy Animal.prototype without calling the constructor. and using Object.create is the answer.

References

Leave JavaScript - Object.create in `Class`ical Inheritance to:

Written by

Developer

Read more #programming posts


Best Posts From Heejin

We have not curated any of heejin's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.

More Posts From Heejin