Thursday, August 29, 2013

Don't rely on Underscore for Your JavaScript Privates

In reference to using the "_" prefix to denote private variables in JavaScript.

My assumption is that no one really believes these are private variables so the underscore is just about saying "please don't mess with me… I really should be private but I cannot figure out how to do that with this darned language."

Well maybe not, however, if privacy is what is desired there is a simple way to do it using a combination of closures and binding.

The following is an example of using the underscore:
function Person(name) {
 this.name = name;
 
 this._init();
}

Person.prototype = {
 _init: function () {
  console.log("init person", this.name);
 }
};
Here is an example of the exact same functionality without exposing the _init method:
var Person2 = (function () {
 function Person(name) {
  this.name = name;
  init.apply(this);
 }
 
 Person.prototype = {
 };
 
 function init() {
  console.log("init person", this.name);
 }
 
 return Person;
}());
You can inspect the log to see the difference:
var p1 = new Person("John");
var p2 = new Person2("Frank");
console.log(p1);
console.log(p2);
Here is a jsFiddle: http://jsfiddle.net/jhorback/Y3jxv/