Advertisement

Quick Tip: Private Variables in JavaScript

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →

Because of JavaScript's dependence upon globals, it might be easy to forget that creating private variables can be accomplished quite simply, thanks to closures. In just a few minutes, I'll demonstrate two common techniques which allow for private variables and methods in your projects.

The key to this particular method is to create a variable that is equal to the returned value of a function. That way, we can specifically choose with values and methods are available to our object. Thanks to closures, we'll still have access to these private variables, even after the object has been returned from our singleton.

var MyObj = function() {
  
// Private variables
  var priv1 = 'private 1',
      priv2 = 'private 2';
  
// Only the methods and properties within this object will be available.
  return {
    doSomething : function() {
      // alert(priv1); // private 1
      alert(this.someProp); // someValue
    },
    
    someProp : 'someValue'
  }
  
}(); // execute the function when the MyObj variable is initialized.
  
  MyObj.doSomething();

View a live demo.

Advertisement