Home > Web Front-end > JS Tutorial > js function definition function usage experience_javascript skills

js function definition function usage experience_javascript skills

WBOY
Release: 2016-05-16 18:29:21
Original
1469 people have browsed it
1. The most basic one is used as a separate function declaration.
Copy code The code is as follows:

function func(){}
Or
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 closure:
Copy code The code is as follows:

(function(){
//Independent scope
})();

4. Can be used as an option Device usage:
Copy code 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);}
};//Avoid repeated judgments

5. Mixed application of the above four situations:
Copy code The 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 the js script returned by ajax:
Copy the code The code is as follows:

var ajax_js_code=
"{a:'a','b':'b','func':function(){alert('abc')}}";
//Assume this is the responseText returned by the server
ajax_js_code=
"return " ajax_js_code;
//Reconstruct the main body of the code, and there can be different reconstruction methods as needed
var ajax_exec=new Function(ajax_js_code );
var result=ajax_exec();
alert(result.a ":" result.b);
result.func();

This kind of construction function Method: var func=new Function(args1,args2,args3,...,body) args: parameters (any number); body: function body
For example: var func=new Function("arg1","arg2 ","alert(arg1 ':' arg2)"); func("ooo","ppp");
It should be noted that the format of the return code should be paid attention to. According to the processing principle, the return form can be as follows:
Copy code The code is as follows:

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

The above three should be able to handle it Most of the code is gone.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template