4th Street Bar Hive-Bar

Hive-Bar Powered by Hive beta-fdb5b5b

Community post

JavaScript - Object.create in `Class`ical Inheritance

![](https://steemitimages.com/DQmbKysHryZbP5REUvDnMjjpQsC858gcN2zg1p3tFFfeaqz/image.png)

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

7 upvotes $0.03

Replies (1)

Review before signing

Posting as . Signing with . Keychain permission: Posting. Hive Keychain will ask you to approve this action next.


  
Technical details

Operation fingerprint: