JS function definition functions using _javascript tips

Source: Internet
Author: User
Tags function definition
1. The most basic function declared as a Benbon is used.
Copy Code code as follows:

function func () {}
Or
var func=function () {};

2. Use as a class Builder:
Copy Code code as follows:

function class () {}
class.prototype={};
var item=new class ();

3. Use as closures:
Copy Code code as follows:

(function () {
Independent scopes
})();

4. Can be used as a selector:
Copy Code code 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);}
};//avoids repetitive judgments.

5. Mixed applications in the above four situations:
Copy Code code as follows:

var class=new function () {
var privatearg;//static Private variable
function Privatemethod=function () {};//static Private method
return function () {//* true constructor/};

6. Use function to handle the JS script returned by Ajax:
Copy Code code as follows:

var ajax_js_code=
"{A: ' A ', ' B ': ' B ', ' Func ': function () {alert (' abc ')}}";
Suppose this returns responsetext for the server
Ajax_js_code=
"Return" +ajax_js_code;
Refactoring the body of the code to have 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 build function mode: var func=new function (args1,args2,args3,..., body) args: parameters (any number); Body: function Principal
such as: Var func=new Function ("Arg1", "arg2", "Alert (arg1+ ': ' +arg2 ')"); Func ("Ooo", "PPP");
It should be noted that note that the return code format, depending on the principle of return form can be a few:
Copy Code code as follows:

1. (function () {//code}) ()
2.{a: "abc", func:function) {}}//hash list
3.function () {}

The above three should be able to handle 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.