JS function defines the use of functions, to understand this can be further understanding of JS object-oriented knowledge.
1. The most basic is used as a Benbon function declaration.
The code is as follows:
function func () {}
Or
var func=function () {};
2. Use as a class constructor:
The code is as follows:
function class () {}
class.prototype={};
var item=new class ();
3. Use as a closure:
The code is as follows:
(function () {
Independent scopes
})();
4. Can be used as a selector:
The 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:
The 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:
The 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:The code is as follows:
1. (function () {//code}) ()
2.{a: "abc", func:function) {}}//hash list
3.function () {}
The above three types should be able to handle most of the code.
JS function definition functions usage experience