JavaScript Prototypal Inheritance: Object.create() vs Direct Assignment
We set the prototype of the child (such as Bird) to that of the parent (such as Animal) using Object.create
.
Bird.prototype = Object.create(Animal.prototype);
Why don't we directly assign the parent's prototype to the child's prototype like this?
Bird.prototype = Animal.prototype;
If you directly assign Bird.prototype = Animal.prototype
, both Bird.prototype
and Animal.prototype
will refer to the same object.
Any modifications made to Bird.prototype
will directly affect Animal.prototype
, which might not be the desired behavior.
When you use Object.create(Animal.prototype)
, you're creating a new object that inherits directly from Animal.prototype
. This new object serves as the prototype for Bird.prototype
.
This method ensures that if you add properties or methods to Bird.prototype
, it won't affect Animal.prototype
.
Get my free, weekly JavaScript tutorials
Want to improve your JavaScript fluency?
Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.
Join today, and level up your JavaScript every Sunday!
Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.