Skip navigation

Tag Archives: object oriented javascript


this is powerful but at the same time if used without care it is dangerous too. Consider the example snippet below

// define Human class
var Human = function(name) {
    this.name = name;
    this.say = function(){
        return "I am " + this.name;
    };
};
var author = new Human('raja');
var badAuthor = Human('ford');  // new keyword missing

alert(typeof author); // object
alert(typeof badAuthor); // undefined because context changed to window
alert(author.name)  // raja
alert(window.name)  // ford

Notice how missing new keyword changing the context to window object.

Play with it.


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
Follow

Get every new post delivered to your Inbox.

Join 126 other followers