Exploration of private variables/methods in OOP Javascript.

Private Variables

Scoping in Javascript is either function level or global. It doesn't support block scoping. This makes using private variables in a class with the prototype style impossible. As the private variable is inside the constructor function declaration and the prototype functions cannot see it unless the private variable is made public via this. One of the benefits of Object Oriented Programming is encapsulation and the hiding of the inner workings of the business object from the public interface. One way around this limitation is to declare the objects non-literally without prototypes.

function WorkOrder () {
  this.work_complete = null;
  this.invoice_date = null;
  var invoice_state = false;

this.invoice = function(d) { if (this.work_complete != null) { if (d != null && typeof(d) != 'undefined') { this.invoice_date = d; invoice_state = true; } else { throw "Work Order cannot be invoiced with an invalid date."; } } else { throw "Work Order cannot be invoiced unless work is complete."; } }

this.is_invoiced = function() { return invoice_state; } }

The variable invoice_state is private as it is declared with var and not this. Declaring a variable with this makes it public within the object. Because the class is written without prototyping the invoice_state variable is valid within the function scoping limitation of javascript.

To test this object:

wo = new WorkOrder();
alert('Is the work order Invoiced? ' + wo.is_invoiced());
wo.work_complete = new Date();
wo.invoice(new Date());
alert('Is the work order Invoiced? ' + wo.is_invoiced());

Private Methods

Private variables and methods can be set in a Javascript object.

function Rock() {
  this.color = "brown";
  var weight = "25";
   var getRockTemperature = function () {
    return "100F";
  }
   this.getTemperature = function () {
    return getRockTemperature(); 
  }
   this.getWeight = function () {
    return weight;
  }; 
}

The weight variable and getRockTemperature() method are private as they have been declared with a var modifier. The getTemperature(), getWeight() and color variables are public as they have been declared with the this modifier. Since methods and variables are top-level in javascript a function can be set as a variable.
Cam Riley: South Sea Republic. Freedom, liberty, equity and an Australian Republic.