JavaScript stands out among popular programming languages because of its unique usage of prototypal inheritance. In this article, we will dive into the concept of prototypal inheritance and how it differs from the traditional class-based inheritance model used in most object-oriented languages.
What is Prototypal Inheritance?
In JavaScript, every object has a property called prototype
which points to a different object. This different object is known as the “object prototype”. The object inherits properties and methods from its prototype.
For example, let’s consider an object created using the object literal syntax:
const car = {}
or an object created using the new Object
syntax:
const car = new Object()
In both cases, the prototype of car
is Object
. Similarly, if we initialize an array, which is also an object:
const list = []
// or
const list = new Array()
the prototype is Array
.
To verify the prototype of an object, we can use the Object.getPrototypeOf()
and Object.prototype.isPrototypeOf()
methods:
const car = {}
const list = []
Object.getPrototypeOf(car) === Object.prototype
Object.prototype.isPrototypeOf(car)
Object.getPrototypeOf(list) === Array.prototype
Array.prototype.isPrototypeOf(list)
All the properties and methods of the prototype become available to the object that has that prototype.
Understanding the Prototype Chain
In JavaScript, Object.prototype
serves as the base prototype for all objects. For example:
Object.getPrototypeOf(Array.prototype) == Object.prototype
Interestingly, the prototype of Object.prototype
is null
. It’s a special case.
The above example showcases the concept of a “prototype chain” in action. By creating an object that extends Array
, any object instantiated using it will have both Array
and Object
in its prototype chain, inheriting properties and methods from all ancestors.
Apart from using the new
operator or the literal syntax, you can use Object.create()
to instantiate an object. The first argument passed to Object.create()
is the object used as the prototype:
const car = Object.create({})
const list = Object.create(Array)
It’s important to note that you can instantiate an array using Object.create(Array.prototype)
. In this case, Array.isPrototypeOf(list)
will return false
, while Array.prototype.isPrototypeOf(list)
will return true
.
Understanding prototypal inheritance is crucial when working with JavaScript, as it allows for flexible and powerful object-oriented programming.