Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does 'this' keyword work in prototype chain?

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.

like image 940
Mobeen Sarwar Avatar asked Nov 15 '18 13:11

Mobeen Sarwar


1 Answers

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.

like image 75
Quentin Avatar answered Sep 20 '22 15:09

Quentin