Skip to main content
0:04est. 3 min

Chapter 54- Understanding the Prototype

Notes

Let's say we have an object "obj" and we know objects can have properties here we have "prop1" we can access it as obj.prop1 using dot operator. We also know js adds hidden properties and methods. All objects have proto{} (prototype) property. The property is simply a reference to another object call it proto{},
If this object proto{} has another property ie prop2. When we call obj.prop2 the dot operator looks for prop2 referenced on obj itself, it doesn't find it so it next goes to the prototype ie object proto{} and looks for property name prop2 and if it finds it, it returns that.
It looks like prop2 is on our object "obj" but actually it's on our object prototype.
Similarly that proto{} object can also point to another proto{} object and so on and so forth.
Each object can have it's own prototype and may be this proto{} of proto{} have another property prop3
These prop2 and prop3 looks like on our main object but they are actually on the prototype chain.
If we have another object "obj2" it can point to same object as its prototype proto{}. Objects can share same proto{}(prototype) if they want to. So obj2.prop2 will return same property as obj.prop2

Example 1 :
var person = {
firstname: ‘Default',
lastname: ‘Default',
getFullName: function(){
return this.firstname + " " + this.lastname;
}
};



var john = {
firstname : ‘John',
lastname : ‘Doe'
}

//Don't do this EVER, for demo purpose only!!
john.__proto__ = person; //john now inherits from person
console.log(john.getFullName())// John Doe
console.log(john.firstname); //John