Home  >  Article  >  Web Front-end  >  Summary of various calling methods of anonymous functions in Javascript_javascript skills

Summary of various calling methods of anonymous functions in Javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:10:181214browse

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 the function call to execute

Copy code The code is as follows:

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

Method 2, call the function and get Return value. Force the function to be executed directly and then return a reference. The reference is then called and executed
Copy the code The code is as follows:

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

This kind of This method is also a popular calling method used by many libraries, such as jQuery and Mootools

Method 3, use void

Copy the code The code is as follows:

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

Method 4, use - / Operator
Copy code The code is 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 The code is as follows:

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

Finally look at the wrong calling method
Copy code The code is as follows:

function(x,y){
alert(x y );
return x y;
}(3,4);
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