1. The most basic function declaration is used as a local shard.
CopyCode The Code is as follows: function func (){}
Or
VaR func = function (){};
2. Use as a class constructor:
Copy code The 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 code Code: 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:
1. (function () {// code })()
2. {A: "ABC", FUNC: function) {}} // hash
3. function (){}
The above three methods should be able to process most of the Code.