1. The most basic function declaration is used as a local shard.
Copy codeThe Code is as follows:
Function func (){}
Or
Var func = function (){};
2. Use as a class constructor:
Copy codeThe Code is as follows:
Function class (){}
Class. prototype = {};
Var item = new class ();
3. Use as a closure:
Copy codeThe Code is as follows:
(Function (){
// Independent Scope
})();
4. It can be used as a selector:
Copy codeThe Code is as follows:
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 );}
}; // Avoiding repeated judgments
5. Hybrid applications in the above four situations:
Copy codeThe Code is as follows:
Var class = new function (){
Var privateArg; // static private variable
Function privateMethod = function () {}; // static private Method
Return function () {/* real constructor */};};
6. Use Function to process js scripts returned by ajax:
Copy codeThe Code is as follows:
Var ajax_js_code =
"{A: 'A', 'B': 'B', 'function': function () {alert ('abc ')}}";
// Assume that responseText is returned for the server.
Ajax_js_code =
"Return" + ajax_js_code;
// Refactor the code body. You can use different refactoring methods as needed.
Var ajax_exec = new Function (ajax_js_code );
Var result = ajax_exec ();
Alert (result. a + ":" + result. B );
Result. func ();
This Function construction method: var func = new Function (args1, args2, args3,..., body) args: parameter (any number of); body: Function body
For example, var func = new Function ("arg1", "arg2", "alert (arg1 + ':' + arg2)"); func ("ooo ", "ppp ");
Note that the format of the returned code can be as follows:
Copy codeThe Code is as follows:
1. (function () {// code })()
2. {a: "abc", func: function) {}} // hash
3. function (){}
The above three methods should be able to process most of the Code.