javascript – namespacing, public and private data

This is quick code sample of public and private data using javascript. You would create anonymous call back function. Private data would be store in var.
Public data would be returned.

// we create anonymous callback function to create private and public functions
var THINGS = function() {
// private
var gifts = 3;
// public
return {
    gems: 1000,
    gold: 2000,
    swords: 300,
    SECRET: {
      open: function() {
        gifts--;
        alert('OPENED!');
      }
    }
};}();

I hope you found this code snippet useful in your coding. These are higher order examples of code has to deal with object orientated programming. You can apply these concepts elsewhere.

Public functions can be access and changed anywhere. Where as private can’t be changed the numbers stay static. For example gifts will stay 3, but the public function can subtract it in increments of negative 1.

The reason behind public and private is track bugs. If you have too many public/global variables you get lost quick and other variables can overwrite those current variables, which is something you don’t want. Plus there is name spacing here the namespace is THINGS.

Leave a Reply