Eitanos30
Eitanos30

Reputation: 1439

What are the difference between adding a property to instance or adding to prototypeproperty?

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.

  1. or adding the following line outside the class declaration:

    PersonCl.prototype.species = "Male";

Upvotes: 0

Views: 68

Answers (2)

Pointy
Pointy

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

dm.shpak
dm.shpak

Reputation: 355

  1. Prototype is a real object
  2. A lot of objects could have the same prototype
  3. Prototype could have prototype too
  4. When you read object property JS will look for own property first, and if it does not exists, it will look for this property in prototype and in prototype of prototype, etc.

Upvotes: 0

Related Questions