Javascript private and public members | Dynamic name spacing
Published by Nicholas Dunbar on February 10th, 2014
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 = {};
var myApp = {};
(function(context) {
//private member
var id = 0;
var id = 0;
//public member function
context.next = function() {
return id++;
};
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:
)
Result in console:
0, 1, undefined, 0, undefined