Understanding Prototypes in JavaScript for Object Construction
In JavaScript, constructors enable the creation of template objects known as prototypes. When a constructor function is defined, an object is automatically created in memory representing its prototype. The constructor holds a prototype property referencing this object, while the prototype includes a constructor property pointing back to the constructor. Accessing a constructor's prototype can be done via ConstructorFunction.prototype.
Link Between Constructor and Prototype
function Human(name, age) {
this.name = name;
this.age = age;
this.consume = function(item) {
console.log(`${this.age} year old ${this.name} is eating ${item}`);
};
}
console.log(Human); // Constructor function object
console.log(Human.prototype); // Associated prototype object
Relationship of Instances to Prototype
Every instance generated from a constructer carries an internal reference, accessible as __proto__, which links it to the shared prototype. When accessing a property or method, if the instance lacks it locally, the lookup proceeds to the prototype. This mechanism allows augmentation of all instances by modifying the prototype.
<script>
function Human(nick, yrs) {
this.nick = nick;
this.yrs = yrs;
this.consume = function(thing) {
console.log(`${this.yrs} year old ${this.nick} is consuming ${thing}`);
};
}
// Inspect constructor and prototype
console.log(Human);
console.log(Human.prototype);
// Extend prototype with new property and method
Human.prototype.sex = 'Male';
Human.prototype.rest = function() {
console.log(`${this.yrs} year old ${this.sex} individual ${this.nick} is sleeping`);
};
const indA = new Human('Alice', 12);
indA.consume('puff pastry');
indA.rest();
const indB = new Human('Bob', 9);
indB.consume('croissant');
indB.rest();
console.log(indA);
console.log(indB);
</script>
By assigning properties or methods to the prototype, all current and future instances gain access without redefining them within each object, enabling efficient memory usage and consistant behavior across instances.