According to my knowledge, prototypes enable a JS object to inherit properties and methods from another. In the below program I am defining a constructor function and then add 'age' property into it's prototype object. Next, I changed the age property of the first object. When I display data the age property of fist and second, NodeJS displayed 30 and 20.
So, is prototype of customer1 and customer2 not reference to the same object?
function Customer(name) { name } Customer.prototype.age = 20; const customer1 = new Customer('customer1'); const customer2 = new Customer('customer1'); customer1.age = 30; console.log(customer1.age); //Return: 30 console.log(customer2.age); //Return: 20
When you request a property on an object, JavaScript checks that object to see if it exists.
If it does, it gives you the value of that property.
If it doesn't exist, it gets the prototype object and checks that for a property with that name. (And if that doesn't exist, it checks that objects prototype, and so on and until it finds a property or runs out of prototype objects).
The prototype is a reference to the same object for both instances of Customer, but when you write customer1.age you are writing that to customer1 and not to the prototype.