Showing posts with label object oriented js. Show all posts
Showing posts with label object oriented js. Show all posts

Thursday, January 7, 2016

Object Oriented Java Script

Below is the best sample for declaring makeCounter class and creating two objects counter1 and counter2 of the same.

Here this class returns three closure functions increment, decrement and value which share a common environment consisting of one private variable privateCounter and private method changeBy.

var makeCounter = function() {
  var privateCounter = 0;
  function changeBy(val) {
    privateCounter += val;
  }
  return {
    increment: function() {
      changeBy(1);
    },
    decrement: function() {
      changeBy(-1);
    },
    value: function() {
      return privateCounter;
    }
  }  
};

var counter1 = makeCounter();
var counter2 = makeCounter();
alert(counter1.value()); /* Alerts 0 */
counter1.increment();
counter1.increment();
alert(counter1.value()); /* Alerts 2 */
counter1.decrement();
alert(counter1.value()); /* Alerts 1 */

alert(counter2.value()); /* Alerts 0 */


Closure

It is an inner function that has access to the variables/ of outer function.

Closures can be used to allow public functions to access private methods and variables.

* Took notes from http://developer.mozilla.org