One thing we could always appreciate in the days of constructor functions was the ability to extend a constructor’s prototype, even on the fly, after instances have been created. Any addition to the prototype object will be immediately accessible in all instances, not just new ones.
This is very practical since rather than every instance having copies of the methods (and shared properties) only one exists in the prototype and does not need to be replicated. The memory savings can be substantial.
const numberOps = function (a, b) {
this.a = a;
this.b = b;
}
const u = new numberOps(6, 7)
const v = new numberOps(3, 14)
We’ve got two instances in effect for the entire session. Now we can add a shared property:
numberOps.prototype.c = 42
console.log(u.c) // 42
console.log(v.c) // 42
Cool, eh?
But what about the methods?
numberOps.prototype.add = function () {
return this.a + this.b;
}
numberOps.prototype.mul = function () {
return this.a * this.b;
}
console.log(u.add()) // 13
console.log(v.add()) // 17
console.log(u.mul()) // 42
console.log(v.mul()) // 42
Truly fun stuff! We can apply the same general thinking to ES6 class
constructors, as well, but it takes a little working around. Seems some months ago I wrote a post demonstrating this. If it hasn’t been archived it might come up on search.