Js function-defined functions

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.