JavaScript Functions

Here I explain different types of function creation methods in JavaScript

Create a basic function 

  1. function myFunction() {  
  2.    alert("myFunction called");  
  3. }  
  4.   
  5. myFunction(); //call function  

Call a function when window load

  1. function init() {  
  2.    alert("init called");  
  3. }  
  4.   
  5. window.onload = init;  
Call anonymous function when window load
  1. window.onload = function () {  
  2.    alert("anonymous function called");  
  3. };   

Call a function with setTimeout

  1. function tOut() {  
  2.    alert("tOut function called after 1000 milliseconds")  
  3. }  
  4.   
  5. setTimeout(tOut, 1000);   
Call anonymous function with setTimeout
  1. setTimeout(function(){ alert("anonymous function called after 1000 milliseconds"); },1000);  

Create an inner function

  1. function outer() {  
  2.   
  3.    alert("outer - before");  
  4.   
  5.    function inner() {  
  6.       alert("inner");  
  7.    }  
  8.   
  9.    inner(); // can call inner  here  
  10.    alert("outer - after");  
  11.   
  12. }  
  13.   
  14. outer();  
  15. //inner(); // cannnot call inner here   
  1. var inn;  
  2.   
  3. function outer() {  
  4.    alert("outer - before");  
  5.   
  6.    function inner() {  
  7.       alert("inner");  
  8.   
  9.    }  
  10.   
  11.    inn = inner;  
  12.    alert("outer - after");  
  13.   
  14.   
  15. }  
  16. outer();  
  17. inn(); // call inner here  

  1. var f = function () {  
  2.    alert("f")  
  3. };  
  4.   
  5. f(); //call  
  1. var f = function myFunction() {  
  2.    alert("myFunction")  
  3. };  
  4.   
  5. f();  

  1. var ob = {};  
  2. ob.func = function(){  alert("func") };  
  3. ob.func(); //call  
  1. var ob = {  
  2.     f1 : function(){ alert("f1"); },  
  3.     f2 : function(){ alert("f2"); }  
  4. }   
  5.   
  6. ob.f1(); // call  
  1. var ob = {  
  2.     f1 : function myFunction(){ alert("myFunction called"); }   
  3. }  
  4. ob.f1(); // call  

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

  1. function myFunc(){  
  2.       
  3.     for(var x in arguments){  
  4.         alert(arguments[x]);  
  5.     }  
  6.   
  7. }  
  8.   
  9. var o1 = {};  
  10. var o2 = {};  
  11.   
  12. myFunc.apply(o1,[1,2,3]);  
  13. myFunc.call(o2,1,2,3);   

ReferenceSecrets of the JavaScript Ninja

No comments:

Post a Comment