Javascript anonymous function application sample introduction


Javascript anonymous function, that is, the function does not have a name, the following list of test code



function debug(data) {
console.log(data);
}

But some functions, it just happens to be written like this


(function(x, y) {
debug(x + y);
})

That’s what we call an anonymous function


var fun = null;
(function() {
var test = function(x ,y ) {
debug(x +y);
}
fun =test;
})();

At this point you type in the fun in the browser console, and you’ll see that it prints function(x, y){debug(x +y); } so obviously this is a function, if you type in fun(1, 2); At this point, I’m going to print out a 3. Now let’s look at the types.


var U = {
uid: 32812,
gameList: (function(){
var list = new Array();
list[7]= '360';
list[6]='baidu';
if(list != 'null'){
return list;
}
}
)(),
serverList: (function(){
var list = new Array();
list[1188]='360';
list[1165]='baidu';
if(list != 'null'){
return list;
}
}
)(),
channelList: (function(){
var list = new Array();
list[9]=' Hand them ';
return list;
}
)(),
searchName : function(t,id){
if( id == false || /^d+$/.test(id) == false ){
return ' This is a function ';
}else if(eval(t).hasOwnProperty(id)){
return eval(t)[id];
}else{
return 'test';
}
}
};

At this point, you type U in the console; You’ll see that this is an array. U[‘searchName ’] is a function, and U[‘qudaoList’] returns a result.