JavaScript Functions

Here I explain different types of function creation methods in JavaScript

Create a basic function 

function myFunction() {
   alert("myFunction called");
}

myFunction(); //call function

Call a function when window load

function init() {
   alert("init called");
}

window.onload = init;
Call anonymous function when window load
window.onload = function () {
   alert("anonymous function called");
}; 

Call a function with setTimeout

function tOut() {
   alert("tOut function called after 1000 milliseconds")
}

setTimeout(tOut, 1000); 
Call anonymous function with setTimeout
setTimeout(function(){ alert("anonymous function called after 1000 milliseconds"); },1000);

Create an inner function

function outer() {

   alert("outer - before");

   function inner() {
      alert("inner");
   }

   inner(); // can call inner  here
   alert("outer - after");

}

outer();
//inner(); // cannnot call inner here 
var inn;

function outer() {
   alert("outer - before");

   function inner() {
      alert("inner");

   }

   inn = inner;
   alert("outer - after");


}
outer();
inn(); // call inner here

var f = function () {
   alert("f")
};

f(); //call
var f = function myFunction() {
   alert("myFunction")
};

f();

var ob = {};
ob.func = function(){  alert("func") };
ob.func(); //call
var ob = {
    f1 : function(){ alert("f1"); },
    f2 : function(){ alert("f2"); }
} 

ob.f1(); // call
var ob = {
    f1 : function myFunction(){ alert("myFunction called"); } 
}
ob.f1(); // call

Call function using apply and call(not work on IE)

function myFunc(){
    
    for(var x in arguments){
        alert(arguments[x]);
    }

}

var o1 = {};
var o2 = {};

myFunc.apply(o1,[1,2,3]);
myFunc.call(o2,1,2,3); 

ReferenceSecrets of the JavaScript Ninja

No comments:

Post a Comment