I’ve been using this pattern whenever I need to create a class that might need to be instantiated multiple times and I want to prevent private methods from being accessed outside of the object.
What’s the name for this JavaScript pattern?
var baseball = (function() {
var _add = function(value) {
value = value + 5;
return value;
};
var constructor = function(iVal) {
this.baseball = true;
this.num = iVal;
};
constructor.prototype.add = function() {
this.num = _add(this.num);
};
return constructor;
})();
var test = new baseball(5);
var testb = new baseball(6);
The names, values and methods in the example above are completely meaningless; I just want to illustrate the syntax, structure, and usage of the pattern.
This is a module pattern, almost a revealing module pattern. See the linked pages by Addy Osmani for information about it and many other useful Javascript design patterns.