There are several good ways to define a function


4 ways to define a function

1. The most basic use as a separate function declaration.

The copy code is as follows:


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

2. Use as a class constructor:

The copy code is as follows:


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

3. Used as a closure:

The copy code is as follows:


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

4. Can be used as a selector:

The copy 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 duplicate judgments

5. Mixed application of the above four situations:

The copy code is as follows:


var class=new function(){
var privateArg;//Static private variable
function privateMethod=function(){};//Static private method
return function(){/* A true constructor *