What is a prototype in JavaScript anyway?
Let us look at the mystery of __proto__, [[prototype]] & prototype
[PS] This article promotes a YouTube channel I am working on. More of a link to the video sort of.
Nearly all objects in JavaScript are instances of
Object
; a typical object inherits properties (including methods) fromObject.prototype
[[prototype]] && __proto__
The __proto__
getter function exposes the value of the internal [[Prototype]]
of an object. For objects created using an object literal, this value is Object.prototype
The __proto__
setter allows [[Prototype]]
of an object to be mutated. The object must be extensible according to Object.isExtensible()
: if it is not, a TypeError
is thrown. The value provided must be an object or null
. Providing any other value will do nothing.
The use of __proto__
is controversial and discouraged. It was never originally included in the ECMAScript language spec, but modern browsers implemented it anyway. Only recently was the __proto__
property standardized by the ECMAScript 2015 specification for compatibility with web browsers, so it will be supported into the future. It is deprecated in favor of Object.getPrototypeOf
/Reflect.getPrototypeOf
and Object.setPrototypeOf
/Reflect.setPrototypeOf
(though still, setting the [[Prototype]]
of an object is a slow operation that should be avoided if performance is a concern).
The __proto__
property can also be used in an object's literal definition to set the object [[Prototype]]
on creation, as an alternative to Object.create()
.
In this video, let us talk about & see what is a prototype? We will see what is __proto__, what is the hidden property [[prototype]] & what is a function prototype? Let us also understand what is prototype chain & how it helps in prototypal inheritance in JavaScript.