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

js function usage experience_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:27:451165browse

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 a closure:
Copy code The code is as follows:

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

4. Can be used as a selector:
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 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, there are different reconstruction methods according to needs
var ajax_exec=new Function(ajax_js_code);
var result=ajax_exec();
alert(result.a " :" result.b);
result.func();


This way of constructing a function: 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 can be as follows. According to the processing principle, there are several return forms:
1.(function(){//code})()
2.{a:"abc",func:function){}}//Hash table
3.function(){}
The above three should be able to handle most codes.
Statement:
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