Home > Web Front-end > JS Tutorial > body text

Javascript中匿名函数的调用方法介绍

巴扎黑
Release: 2017-08-09 14:18:13
Original
1728 people have browsed it

Javascript中定义函数的方式有多种,函数直接量就是其中一种。如var fun = function(){},这里function如果不赋值给fun那么它就是一个匿名函数。好,看看匿名函数的如何被调用。 

方式1,调用函数,得到返回值。强制运算符使函数调用执行

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

 

方式2,调用函数,得到返回值。强制函数直接量执行再返回一个引用,引用再去调用执行

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

这种方式也是很多库爱用的调用方式,如jQueryMootools

 

方式3,使用void

1
2
3
4
voidfunction(x) {
      x = x-1;
      alert(x);
}(9);

 

方式4,使用-/+运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
-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);

 

方式5,使用波浪符(~)

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

 

最后看看错误的调用方式

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

The above is the detailed content of Javascript中匿名函数的调用方法介绍. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!