JS function usage experience

Source: Internet
Author: User

1. The most basic function declaration is used as a local shard. CopyCode The Code is as follows: function func (){}
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.

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.