Reputation: 1439
I have the following class:
class PersonCl {
constructor(fullName, age) {
this.fullName = fullName;
this.age= age;
}
// Instance methods
// Methods will be added to .prototype property
calcAge() {
console.log(2037 - this.birthYear);
}
greet() {
console.log(`Hey ${this.fullName}`);
}
}
now i have lets say two object that were created from the constructor:
const Joe = new PersonCl('Joe',23);
const Larisa = new PersonCl('Larisa',41);
i'm asking what is the difference between:
1.adding the property species into constructor and set it exactly where we set the fullName and age.
or adding the following line outside the class declaration:
PersonCl.prototype.species = "Male";
Upvotes: 0
Views: 68
Reputation: 413720
The "species" property placed on the prototype object will be visible on all instances in most (but not all situations). As soon as your code makes a change to "species":
someInstance.species = "tiger";
then that instance will have a local property "species", and the value of "species" on other instances will not change.
Clearly, when the property is directly added to instances in the constructor, all instances will be similarly initialized (given your sample code) but thereafter changes can still be made on an instance-by-instance basis. The key point is that updating a property value on an object always makes a local, "own" property of that object and does not affect the prototype.
Some methods intended to help work with object properties as a collection, like Object.keys()
, only involve "own" properties, which means properties directly associated with an object and not inherited properties.
Upvotes: 2
Reputation: 355
Upvotes: 0