Skip navigation

Tag Archives: oojs


Definition for closure : A closure is the local variables for a function – kept alive after the function has returned.

A nice example to explain closure.

//
// define a function which preserves data (count)
//
var CreateCounter = function(){
   var count, f;
   count = 0;
   f = function(){
      count = count+1;
      return count;
   }
   return f;
}

// create objects which remembers its own counter
var counter1 = CreateCounter();
var counter2 = CreateCounter();
alert(counter1());  // 1
alert(counter1());  // 2
alert(counter1());  // 3

alert(counter2());  // 1
alert(counter2());  // 2
alert(counter2());  // 3

alert(counter1());  // 4
alert(counter1());  // 5
alert(counter2());  // 4

Nice article about closure found at http://www.jibbering.com/faq/faq_notes/closures.html


In javascript function are first class objects. That means it can be used as values. Notice the example below

// function definition
function alertHi(name) {
   alert('hi! '+name);
}

// storing string
var name = 'rajakvk';

// storing number
var age = 26;

// storing function
var sayHi = alertHi;

// now sayHi is also function, you can call it like
sayHi();   // hi

Here is example to use function as parameter

// define a function to call a function twice
// here function f passed as parameter
var callTwice = function(f,x) {
   return f(f(x));
}
var addTen = function(x) {
   return x+10;
}
// here function addTen used as value 
var y = callTwice(addTen, 2);   // 22

The code below pretty much explains itself. Just follow the comments. You can also run the code snippet in the firefox console tab

// Parent class definition
var Human = function(name, age) {
    this.name = name;
    this.age = age;
}

// Child class definition
var Indian = function(name, state){
    if(name) this.name = name;
    this.state = state;
}

// Extending
Indian.prototype = new Human('raja',22);

// Creating instance of child class with own name property
var tamilian = new Indian('kvk','TN');

// Creating another instance of child class without own property
var cbe_ian = new Indian('','TN');

alert(tamilian.name);  // kvk
alert(tamilian.age);   // 22
alert(tamilian.state); // TN
alert(cbe_ian.name);   // raja