Javascript private and public members | Dynamic name spacing

The following is how to scope an object (called an object literal) with private and public members:

myApp is the class
id is private
next and reset are public functions

//create class
var myApp = {};

(function(context) {
//private member
var id = 0;

//public member function
context.next = function() {
return id++;
};

//public member function
context.reset = function() {
id = 0;
}
})(myApp);

Example:

window.console && console.log(
myApp.next(),
myApp.next(),
myApp.reset(),
myApp.next(),
myApp.id
)

Result in console:

0, 1, undefined, 0, undefined


comments powered by Disqus