Summary of how anonymous functions are called in Javascript


There are many ways to define functions in Javascript, one of which is the function direct. Var fun = function(){}, where function is an anonymous function if it is not assigned to fun. Ok, let’s see how the anonymous function is called.

**Method 1, call the function, get the return value. The force operator causes the function call to execute **

(function(x,y){
    alert(x+y);
    return x+y;
}(3,4));

**Method 2, call the function, get the return value. Force the direct execution of a function to return a reference, which then calls the execution **

(function(x,y){
    alert(x+y);
    return x+y;
})(3,4);

This is also a popular way to call libraries like jQuery and Mootools

**Method 3, use void **

void function(x) {
      x = x-1;
      alert(x);
}(9);

**Mode 4, use the -/+ operator **

-function(x,y){
    alert(x+y);
    return x+y;
}(3,4);

+function(x,y){
    alert(x+y);
    return x+y;
}(3,4);

--function(x,y){
    alert(x+y);
    return x+y;
}(3,4);

++function(x,y){
    alert(x+y);
    return x+y;
}(3,4);

**Mode 5, using tilde (~) **

~function(x, y) {
    alert(x+y);
   return x+y;
}(3, 4);

Finally, look at the wrong invocation

function(x,y){
    alert(x+y);
    return x+y;
}(3,4);