Friday, May 17, 2013

JavaScript Learning #6 - Ways to call a function

This article helps in understanding the importance of  "this", global objects and ways to call a function.

Very nice article @ http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx


Examples:


//Type#1 :
function makeArray(arg1, arg2) {
return [this, arg1, arg2];
}
makeArray("one", "two"); //output: window, one, two
window.makeArray("one", "two"); //output: window, one, two


alert( typeof window.methodThatDoesntExist );
// => undefined
alert( typeof window.makeArray);
// => function


//Type#2: creating the object
var arrayMaker = {
myName: 'Kondal Kolipaka',
make: makeArray
};
arrayMaker.make("one", "two");  //output: [arrrayMaker, one, two]
arrayMaker['make']("one", "two");  //output: [arrrayMaker, one, two]



//Type#3 : 
var arrayMaker2 = {
myName: 'Kondal Kolipaka',
make: function (arg1, arg2) {
    return [this, arg1, arg2];
}
};
arrayMaker2.make("one", "two"); //output: arrayMaker2, one, two



//Type#4
(function () {
   function make(arg1, arg2) {
       return [this, arg1, arg2];
   }
   alert(typeof make);
   // function

   alert(typeof this.make);
   // undefined

   alert(typeof window.make);
   // undefined
})();

alert(typeof make);
// undefined

alert(typeof this.make);
// undefined

alert(typeof window.make);
// undefined


//Type#5
(function(){
/* code */
}());

(function(){
/* code */
})();



No comments:

Post a Comment