There are many ways to define functions in Javascript, and function literals are one of them. For example, var fun = function(){}, if function is not assigned to fun, then it is an anonymous function. Okay, let's see how the anonymous function is called.
Method 1, call the function and get the return value. The coercion operator causes function calls to execute
Copy the code code as follows:
(function(x,y){
alert(x+y);
return x+y;
}(3,4));
Method 2, call the function and get the return value. Force the function to be executed directly and then return a reference, which is then called and executed.
Copy the code code as follows:
(function(x,y){
alert(x+y);
return x+y;
})(3,4);
This method is also a favorite calling method used by many libraries, such as jQuery, Mootools
Method 3, use void
Copy the code code as follows:
void function(x) {
x = x-1;
alert(x);
}(9);
Method 4, use -/+ operator
Copy the code code as follows:
-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);
Method 5, use the tilde (~)
Copy the code code as follows:
~function(x, y) {
alert(x+y);
return x+y;
}(3, 4);
Finally, look at the wrong calling method
Copy the code code as follows:
function(x,y){
alert(x+y);
return x+y;
}(3,4);