I like the general style of using closures to create objects with private properties. What I'm unsure of is whether it's more efficient to create the prototype methods within a closure or on the actual prototype of the object. Consider the following examples:
const A = function(a, b) {
this.a = a;
this.b = b;
};
A.prototype = {
add:function() { this.a += this.b; }
};
const B = (function() {
function add() { this.a += this.b; }
return function(a, b) {
return { a, b, add };
};
})();
Example A is a traditional constructor function with a prototype. Using it looks like this:
var a = new A(1, 1);
a.add(); // a.a == 2;
Example B is the technique using closures. Using it looks like this:
var b = B(1, 1);
b.add(); // b.a == 2;
The way I expect a to work is that each instance of A has a and b properties as well as a pointer to the prototype object which holds the add method.
The way I expect b to work is that each instance of B has a and b properties as well as a pointer to the add method. The B function has a closure that contains the add method. The add method is defined only once when B is defined. This seems like a decent way of creating "prototype" properties and methods in JS. Does anyone know if this is a performant approach to creating objects with "shared" properties or a viable alternative to the traditional approach using prototype?