How does 'this' keyword work in prototype chain?

113 views Asked by At

Hi experts here is my code and I'm stuck how this keyword is adding property to a object.

function carMaker(){
 this.companyName='Lamborghini'; 
 }
 let LamborghiniUrus = new carMaker();
 carMaker.prototype.country="Italy"
 LamborghiniUrus.price="200000";

I know property added with this and Object.prototype is inherited to all objects but does both are equivalent i.e, this is also adding property to prototype?

If yes then why console.log(carMaker.prototype.companyName) is undefined.

If no then how we can access a property added with thisin the same object(in carMake fuction in my case).

And also does this.companyName='Lamborghini' and LamborghiniUrus.price="200000" are equivalent.

1

There are 1 answers

9
Quentin On BEST ANSWER

In combination with new, this refers to the object you are creating.

So this.companyName='Lamborghini' sets a property on the actual instance.

When you try to read a property from an object, it first attempts to read the property from the object itself. If it doesn't find one, it looks up the prototype chain until it finds an object with that property (or runs out of prototypes).

Writing a property to an object doesn't touch anything up the prototype chain.