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 a closure:
(function(){
//Independent scope
})();
4. Can be used as a selector:
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, there are different reconstruction methods according to needs
var ajax_exec=new Function(ajax_js_code);
var result=ajax_exec();
alert(result.a " :" result.b);
result.func();
This way of constructing a function: 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 can be as follows. According to the processing principle, there are several return forms:
1.(function(){//code})()
2.{a:"abc",func:function){}}//Hash table
3.function(){}
The above three should be able to handle most codes.