Day 67 JavaScript Prototypes

Along with functional programming, I revisited object-oriented programming in JavaScript. Some conceptual asides that are prerequisites to understanding object orientation is an understanding inheritance, prototypes, and objects on a deeper level.

Inheritance is one object that gets access to the properties and methods of another object.

All objects in JavaScript have properties and always have a prototype. The prototype is simply a reference to another object. It’s an object that stands on its own. You can use it on its own. It’s the object that the original object can grab and be able to get its properties and methods. So if the prototype object had another property or property 2. When you call for property 2 the dot operator looks for property 2 referenced on the first object itself. It doesn’t find it so it next goes to the prototype and if it finds it, it returns it. Similarly, that prototype object itself can also point to another object and so forth which would be another prototype with a property. This creates a prototype chain.

Similar to a scope chain which looks to see where we have access to a variable. However, a prototype chain sees where we have access to a property or method amongst the sequence of objects that are connected via the prototype property. The prototype chain is hidden from us. In the sense that we don’t have to go obj.proto.proto.prop3. We can just say obj.prop3 and the JavaScript engine does the work of searching the prototype chain.

Interestingly all objects can share prototype properties and methods. For example, obj2.prop2 would also reference the same spot in memory as obj.prop2. So they’re literally sharing a property but not directly. They are connected via the prototype chain.

So simply put all objects have a reference to another object and we call that its prototype, where it goes and looks for properties and methods if not found on the original object.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Up ↑

%d bloggers like this: