JavaScript Prototypes
Introduction to JavaScript prototypes and their uses.
We'll cover the following...
Background
We know about JavaScript objects and their mutation. We have assigned properties from one object to another. The question still remains. Is there a neater way of having all properties of another object?
Introduction to prototypes
All JavaScript objects have the property prototype. They go under the property name __proto__
. The prototype of each object is assigned during creation and is itself an object. Look at the following code.
let vehicle = { wheels : 4 }; // object assigned to variable named vehiclelet car = { seats : 5 }; // object assigned to variable named carlet driver = {} // empty object assigned to variable named driver// Print all objects and __proto__ property for each variableconsole.log(`vehicle:`, vehicle, vehicle.__proto__);console.log(`car:`, car, car.__proto__);console.log(`driver:`, driver, driver.__proto__);
In the code above, each object is assigned to the three variables: vehicle
, car
, and driver
(lines 1 to 3). We also print the __proto__
property for each variable, which is otherwise hidden when printing an object including an empty object (driver
). The __proto__
property for each object can be seen as an empty object because the properties of the prototype object are ...