In short, you can use private variables when you return another scope when declaring a class.

function Cats() {
    var nameList = []; // private var
      
    // This is where you define another scope!
    return {
      add:function(name) {
        nameList.push(name);
      }
    } 
  }

How does it work?

The magic lies in creating a different scope at the end of the class definition that does not include private variables. Then, private members are available in this scope and not outside of it, thanks to the power of closures.

Differences between private and public

These two classes definition shows the difference between the a class where all members are public versus a class where some members are private.

This is a class where all members are public.

function PublicCats() {
    // This is the list of cat names
    this.nameList = [];
    
    // This is a method that I would like to be private but can't
    // It returns the last cat of the list
    this.lastCat = function() {
      return this.nameList[this.nameList.length-1];
    }
    
    // Return the list of names
    this.names = function() {
      return this.nameList;
    }
    
    // Add a name to the list
    this.add = function(name) {
      this.nameList.push(name);
      
      // Return the last cat just added
      return this.lastCat();
    }  
  }

This is the corresponding class where some members are private.

function PrivateCats() {
    // This is the list of cat names
    var nameList = [];
    
    // This is a private method
    var lastCat = function() {
      // Note : I don't use "this" to access private variables
      // thanks to the power of closures!
      return nameList[nameList.length-1];
    }
    
    // These are our public methods!
    // This is where we create another scope to
    // avoid external objects to use the private variables.
    return {
      add:function(name) {
        // Note : once again, I don't use "this" 
        // to access the private variables and methods
        nameList.push(name);
        return lastCat();
      },
      names:function() {
        return nameList;
      }
    }  
  }

In the above code, line 15 makes all the difference between the two classes.

On GitHub

Get all the code on GitHub and see it live in action on my GitHub page.

comments powered by Disqus