function Analysis of JS language

Source: Internet
Author: User

1. The most basic is used as a Benbon function declaration.

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 scopes
})();


4. 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);}
};//avoids repeated judgments.


5. Mixed application of the above four conditions:

Copy CodeThe code is 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 process the JS script returned by Ajax:

Copy CodeThe code is as follows:
var ajax_js_code=
"{A: ' A ', ' B ': ' B ', ' Func ': function () {alert (' abc ')}}";
Assume that this is the server return ResponseText
Ajax_js_code=
"Return" +ajax_js_code;
Refactor the code body and can 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 constructor method: Var func=new function (args1,args2,args3,..., body) args: parameter (any number); Body: Function Body
such as: Var func=new Function ("Arg1", "arg2", "Alert (arg1+ ': ' +arg2)"); Func ("Ooo", "PPP");
It should be noted that note the format of the return code, depending on the processing principle return form can have a few:

Copy CodeThe code is as follows:
1. (function () {//code}) ()
2.{a: "abc", func:function) {}}//hash list
3.function () {}

function Analysis of JS language

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.