2️⃣

1.2 Object Prototype Chain

1.2 Object Prototype Chain

Javascript is sometimes called a prototype-based language, because Javascript objects function using a prototype chain. Every object has a private property that links it to a prototype object; and that prototype object has its own prototype object. This continues until we reach null, which is at the very end of the prototype chain.
So what are prototype objects? Prototype objects store a list of predefined properties and methods. When we call an object’s property (or a method on the object), the Javascript interpreter will not just search within the object for the property (or method), but also look in the object’s prototype, the prototype’s prototype, etc. until the property is found or the end of the prototype chain is reached. This is the reason why when trying to use a method we did not define on a object, it sometimes works:
let myCubeObject = { sideLength: 8; sayHi() { console.log(“Hi!”); } } console.log(myCubeObject.toString());
The toString method Object.prototype, the prototype of the general object.
Now, we don’t need to use prototypes to create objects. In the next section, we will discuss how to construct Javascript objects using classes. Nonetheless, it is helpful to understand the prototype chain to know how Javascript objects work.
 

Previous Section

Next Section

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.