Private Instance Method Variables

05/06/2014, Tue
Categories: #JavaScript

Instances Methods and Their Personal State

This post is for intended for JavaScript (not Java).

One may put instance method variables within an instance method to provide encapsulation, but what do you do when you want to maintain a private state for each instance method on each instance method execution?

The technique in achieving such a task involves wrapping an instance method and its variable within a function as shown below. The result will produce instance method variables that are truly private to the instance method.

The instance method gets attached to the constructor by using the 'this' reference to the constructor.

Each instance function is then placed into an internal array and the array is looped over to execute and initialize each wrapper function and its corresponding static methods and variables.

// Instance Variables

var Time = function () {
  // Reference the context
  var _this = this;

  // Internal array which houses all instance methods
  // Wrapping all instance methods in a function to
  // contain its private variables for instance methods
  var _time = [
    function () {
      // Private variables for instance
      var privateStaticVar = "Time in milliseconds is ";

      // A instance method of the Time constructor
      _this.getTimeInMilliseconds = function () {
        return privateStaticVar + Date.now();
      };
    },
    // Add more functions within this array
    // for other instance methods
  ];

  // Initialize all instance methods
  for (var i = 0; i < _time.length; i++) {
    _time[i]();
  }
};

var time = new Time();

console.log(time.getTimeInMilliseconds());