javascript - Emulating private methods with closures vs public methods in objects -
as mdn states closures used emulate private methods module pattern:
var counter = (function () { var privatecounter = 0; function changeby(val) { privatecounter += val; } return { increment: function () { changeby(1); }, decrement: function() { changeby(-1); } }; }());
however, instead of using module pattern can create class instead. advantage of creating class on using module pattern?
function counter() { var privatecounter = 0; function changeby(val) { privatecounter += val; } this.increment = function() { changeby(1); }; this.decrement = function() { changeby(-1); }; } var counter = new counter();
what advantage of creating class on using module pattern?
the advantage of creating class on using module pattern can create several instances of class:
var counter1 = new counter; var counter2 = new counter;
each instance have own set of private variables.
on other hand, when use module pattern, creating single object (often called singleton, namespace or module). again, has it's own set of private variables.
both module pattern , class have own uses. module pattern useful creating modules, manager objects (of 1 instance must exist), etc.
the class pattern useful creating new data structures of same type. example, linked list data structure modeled class , not singleton or module.
Comments
Post a Comment