I'm confuse in using Prototype

function Human(firstName, lastName){
    this.firstName = firstName;
    this.lastName = lastName;
    this.sayName = function(){
        return `${this.firstName} ${this.lastName}`;      
    }
}

Human.prototype.sayName = function(){
  return `${this.firstName} ${this.lastName}`;
}

const myself = new Human('Bilal','Shuja');
const father = new Human('Muhammad','Shuja');

what is the difference ? Like writing the method in the function and writing the method with the help of prototype !
All the constructor function instances inherit the method in the same way ! So what is the point of using Prototype ?

when you add something to the prototype, then it exist only once

if you instead add a method in the contructor, then when you make an instance of it that method is copied in each instance

using the prototype is more performant

You mean … prototype save memory ?.. rather the memory consumed by constructor method instances ?

case one, the constructor has the method:

second case, the prototype has the method:

here both objects point to the same thing, meaning it appear only once in memory - now you have only 2 objects, but if you have 100 it saves a significantly higher amount of memory

[images from pythontutor]

1 Like

#ieahleen you are awesome!!