Create a basic function
function myFunction() { alert("myFunction called"); } myFunction(); //call function
Call a function when window load
Call anonymous function when window loadfunction init() { alert("init called"); } window.onload = init;
window.onload = function () { alert("anonymous function called"); };
Call a function with setTimeout
Call anonymous function with setTimeoutfunction tOut() { alert("tOut function called after 1000 milliseconds") } setTimeout(tOut, 1000);
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);
Reference: Secrets of the JavaScript Ninja
No comments:
Post a Comment