Introduction to Prototypes in JavaScript
Understanding Prototypes in JavaScript
When we create a class using a constructor function, memory pre-allocates an object caled the prototype object. The constructor function has a prototype property pointing to this object, and the prototype object has a constructor property pointing back to the constructor function. You can access a class's prototype via ClassName.prototype.
Relationship Between Constructor and Prototype
// Constructor function
function Person(name, age) {
this.name = name;
this.age = age;
this.eat = function(food) {
console.log(`${this.age} year old ${this.name} is eating ${food}`);
};
}
console.log(Person); // Constructor (function) object
console.log(Person.prototype); // Prototype object
Relationship Between Instances and Prototype
Every instance of a class has an internal __proto__ property pointing to their prototype. When accessing a property or method on an object, if its not found on the object itself, the lookup continues to the prototype. Therefore, we can add properties and methods to the prototype to share them among all instances of a class.
// Add properties and methods to the prototype
Person.prototype.gender = 'male';
Person.prototype.sleep = function() {
console.log(`${this.age} year old ${this.gender} child ${this.name} is sleeping`);
};
const p1 = new Person('Alice', 10);
p1.eat('egg tart');
p1.sleep();
const p2 = new Person('Bob', 8);
p2.eat('croissant');
p2.sleep();
console.log(p1);
console.log(p2);
In the example above, gender and sleep are defined on the prototype, so all instances share them. The eat method is defined inside the constructor, so each instance has its own copy.