1. The most basic one is used as a separate function declaration.
function func(){}
Or
var func=function(){};
2. Use as a class constructor:
function class(){}
class.prototype={};
var item=new class( );
3. Use as closure:
(function(){
//Independent scope
})();
4. Can be used as an option Device usage:
var addEvent=new function( ){
if(!-[1,]) return function(elem,type,func){attachEvent(elem,'on' type,func);};
else return function(elem,type,func ){addEventListener(elem,type,func,false);}
};//Avoid repeated judgments
5. Mixed application of the above four situations:
var class=new function(){
var privateArg;//Static private variable
function privateMethod=function(){};//Static private method
return function(){/*real constructor*/};};
6. Use Function to process the js script returned by ajax:
var ajax_js_code=
"{a:'a','b':'b','func':function(){alert('abc')}}";
//Assume this is the responseText returned by the server
ajax_js_code=
"return " ajax_js_code;
//Reconstruct the main body of the code, and there can be different reconstruction methods as needed
var ajax_exec=new Function(ajax_js_code );
var result=ajax_exec();
alert(result.a ":" result.b);
result.func();
This kind of construction function Method: var func=new Function(args1,args2,args3,...,body) args: parameters (any number); body: function body
For example: var func=new Function("arg1","arg2 ","alert(arg1 ':' arg2)"); func("ooo","ppp");
It should be noted that the format of the return code should be paid attention to. According to the processing principle, the return form can be as follows:
1.(function(){//code}) ()
2.{a:"abc",func:function){}}//Hash table
3.function(){}
The above three should be able to handle it Most of the code is gone.