Prototype and Inheritance in JavaScript
Table of Contents
Prototype #
In JavaScript, every object has a hidden built-in property called prototype ([[Prototype]]
in ECMAScript Specification and Chrome, <prototype>
in Firefox), which is an object. With prototypes, we can create shared properties. To get or set [[Prototype]]
, use Object.getPrototypeOf()
and Object.setPrototypeOf()
. __proto__
is a non-standard getter/setter of [[Prototype]]
, but it’s implemented by many JavaScript engines.
|
|
Prototype Chain / Inheritance #
An object has a prototype and its prototype also has a prototype. All these prototypes are called the prototype chain. The last prototype’s prototype is null
. An object can inherit properties from multiple prototypes in the prototype chain. When a property is accessed, the object is first checked. If the property is not found, check every prototype in the prototype chain until the property is found. If the property is not found at the end, undefined
is returned.
In the apple example, the prototype chain of apple
is:
|
|
The code below demonstrates the prototype chain:
|
|
Further Reading #
- Object prototypes - Learn web development | MDN
- Inheritance and the prototype chain - JavaScript | MDN
- Prototypal inheritance - javascript.info
Test #
Comments powered by giscus. If comments are not loaded, giscus may be blocked by your Internet service provider.
Comments powered by Disqus. If comments are not loaded, Disqus may be blocked by your Internet service provider.