In our last article, we talked about Prototype Inheritance in Javascript. Today, we’ll take a look at the different ways to create objects in JavaScript and the resulting prototype chain for each method.
Almost all objects in Javascript are inherited from Object
, which sits on top of the prototype chain. The prototype of Object.prototype
is null:
1. Object Literal
The simplest way to create an object is to use the object literal notation. The created object has Object.prototype
as its prototype.
The prototype of Object.prototype
is null
, so the prototype chain is:
x ➞ Object.prototype ➞ null
2. Constructor Functions
Sometimes you'll want to create multiple objects with the same properties. In JavaScript, constructor functions are functions used to create objects when called with the new
keyword. The first letter of a constructor function is capitalized by convention. So, if we create a constructor called Person
, the prototype of the objects created will be Person.prototype
.
The resulting prototype chain is:
johnDoe ➞ Person ➞ Object.prototype ➞ null
3. Object.create()
Because the previous structure looks so similar to classes in other languages, people expected it to behave like real classes, and that was not the case. So in an attempt to make object creation more intuitive in Javascript, ECMAScript 5 introduced Object.create,
a static method that creates a new object from an existing object. The prototype of this object will be the first argument passed to the method.
The resulting prototype chain is:
johnDoe ➞ person ➞ Object.prototype ➞ null
4. The Class Keyword
As an option for using constructor functions, ES2015 introduced a cleaner and more convenient syntax by adding the class keyword (along with others like: super, extends, and constructor), but only as a syntactical sugar. JavaScript remains a prototype-based language and does not provide a class implementation of class-based languages like Java or C++.
Here again, the prototype chain is:
johnDoe ➞ Person ➞ Object.prototype ➞ null
If you want to dive deeper into Javascript object creation, I highly recommend reading all about new operator, classes, and Object.create().
Happy coding!
Author
Rafael Bicalho
Rafael Bicalho is a UI Engineer at Avenue Code. He is a fan of technology, coffee and programming.