JavaScript: Private Static Members, Part 2

Finally, it’s time to finish up the lesson on private static members and methods in JavaScript.

Last time, I introduced the technique of creating and immediately executing a function, using parentheses. I talked a little about returning a function and storing it in a variable.

1.
var myFunc = (function(){
2.
  returnfunction(){
3.
    alert("Hello, World!");
4.
  }
5.
})();
6.
 
7.
alert(myFunc); // "function () … "
8.
 
9.
myFunc(); // Hello, World!

There are a lot of things you can do with this trick, like create interesting bookmarklets. But let’s see how you can use it to protect information on the class level.

Here we’ll take advantage of JavaScript’s scope behavior. Remember that a function uses the variables where it is defined, not executed. Perhaps a better example…

1.
var myFunc = (function(){
  1.   var message = "I’m hidden.";
  2.   returnfunction(){
  3.     alert(message);
  4.   }
  5. })();
  6.  
  7. var message = "I’m visible.";
  8.  
  9. myFunc(); // "I’m hidden."

We can see that the inner function (which is returned from the outer function and set to myFunc) uses the value of message from the block where it was defined, not executed.

Now you should be able to see where this is going. Let’s look at a more complex example, extended from the first part:

1.
var Product = (function(){
  1.     var partNumRegex = /^\d{4}-\d{2}$/;
  2.  
  3.     returnfunction( num )
  4.     {
  5.         var partNum = null;
  6.  
  7.         this.setPartNum = function( n )
  8.         {
  9.             if(partNumRegex.test(n)){
  10.                 partNum = n;
  11.                 returntrue;
  12.             }else{
  13.                 returnfalse;
  14.             }
  15.         }
  16.  
  17.         this.getPartNum = function()
  18.         {
  19.             return partNum;
  20.         }
  21.  
  22.         if(num)this.setPartNum(num);
  23.  
  24.         returnthis;
  25.     }
  26. })();
  27.  
  28. var car = new Product;
  29. car.setPartNum(‘1234-56’);
  30.  
  31. var table = new Product;
  32. table.setPartNum(‘345678’);
  33.  
  34. alert("Car: "+car.getPartNum()); // "Car: 1234-56"
  35. alert("Table: "+table.getPartNum()); // "Table: null"

What’s the advantage here? The variable partNumRegex is not copied by the new operator. In a small example like this, there is not much benefit, but if you had hundreds of Product objects, you could save a significant amount of memory.

There are a few major drawbacks: a public static (class) method cannot access a private static method or variable. For example:

1.
var Product = (function(){
  1.     var partNumRegex = /^\d{4}-\d{2}$/;
  2.  
  3.     returnfunction(){
  4.         // snip
  5.     }
  6. })();
  7.  
  8. Product.validPartNum = function(num){
  9.     if(partNumRegex.test(num)){// (1)
  10.         returntrue;
  11.     }
  12.     returnfalse;
  13. }

The class method validPartNum has no access to the private class variable partNumRegex, and so will throw an error at (1). Adding an accessor must be done on the instance, not the class, like so:

1.
var Product = (function(){
  1.     var partNumRegex = /^\d{4}-\d{2}$/;
  2.  
  3.     returnfunction(){
  4.         this.getPartNumRegex = function(){
  5.             return partNumRegex;
  6.         }
  7.  
  8.         // snip
  9.     }
  10. })();

But then you cannot access the private variable without first creating an instance of the class, and the accessor function is copied with the new operator. New methods added to the Product.prototype object are likewise unable to access the private static variables. This is a limitation of JavaScript.

Even with these limitations, the ability to hide implementation behind an agreed-upon interface is powerful. (JavaScript doesn’t actually have interfaces, but you can just write it down.) Behind the scenes, you could load new data via Ajax, without ever exposing your Ajax method to that new guy down the hall who likes to misuse everything he can:

1.
var Product = (function(){
  1.     var partNumRegex = /^\d{4}-\d{2}$/;
  2.  
  3.     // private static function, not copied with "new"
  4.     function loadPartData(partNum){
  5.         // load data via Ajax
  6.     }
  7.  
  8.     returnfunction(){
  9.  
  10.         var partNum = null;
  11.  
  12.         // snip
  13.  
  14.         this.setPartNum(num){
  15.             if(partNumRegex.test(num)){
  16.                 partNum = num;
  17.                 var data = loadPartData(partNum);
  18.                 this.productName = data.productName;
  19.                 this.price = data.price;
  20.                 returntrue;
  21.             }else{
  22.                 returnfalse;
  23.             }
  24.         }
  25.  
  26.         // snip
  27.     }
  28. })();

That’s it for now. I owe most of these three articles to the book Pro JavaScript Design Patterns, by Ross Harmes and Dustin Diaz. Those two are geniuses, and anyone who wants to be a better JavaScript programmer would do well to pick up their book.

Next up, I’ll argue why the <dl> tag is a good way to display forms semantically.