Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instance property vs Prototype property [duplicate]

Tags:

javascript

In the below code,

function Person(first, last, age) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
}

Person.prototype.planet = "Earth";

p1 = new Person("David", "Beckham", 39);
p2 = new Person("Lionel", "Messi", 30);

If multiple instances p1 p2 are created using constructor Person, then

How do I understand the difference about the property planet with property age? What difference it would make by adding property planet as this.planet in the constructor Person?

Note: Understanding prototype property

like image 800
overexchange Avatar asked Sep 16 '25 19:09

overexchange


1 Answers

Consider situation when in the fututre we are going to change prototype property that is shared by all instances

function Person(first, last, age) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
}

Person.prototype.planet = "Earth";

p1 = new Person("David", "Beckham", 39);
p2 = new Person("Lionel", "Messi", 30);

console.log(p1.planet) // Earth

Person.prototype.planet = "Mars"

console.log(p1.planet) // Mars
console.log(p1.planet === p2.planet) // true

Changing one property on prototype will change it in all instances

like image 93
Krzysztof Safjanowski Avatar answered Sep 19 '25 10:09

Krzysztof Safjanowski