在 Javascript 中调用匿名函数的各种方法
最编程
2024-07-16 08:52:52
...
Javascript中定义函数的方式有多种,函数直接量就是其中一种。如var fun = function(){},这里function如果不赋值给fun那么它就是一个匿名函数。好,看看匿名函数的如何被调用。
方式1,调用函数,得到返回值。强制运算符使函数调用执行
(function(x,y){ alert(x+y); return x+y; }(3,4));
方式2,调用函数,得到返回值。强制函数直接量执行再返回一个引用,引用再去调用执行
(function(x,y){ alert(x+y); return x+y; })(3,4);
这种方式也是很多库爱用的调用方式,如jQuery,Mootools。
方式3,使用void
void function(x) { x = x-1; alert(x); }(9);
方式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); ++function(x,y){ alert(x+y); return x+y; }(3,4);
方式5,使用波浪符(~)
~function(x, y) { alert(x+y); return x+y; }(3, 4);
方式6,匿名函数执行放在中括号内
[function(){ console.log(this) // 浏览器得控制台输出window }(this)]
方式7,匿名函数前加typeof
typeof function(){ console.log(this) // 浏览器得控制台输出window }(this)
方式8,匿名函数前加delete
delete function(){ console.log(this) // 浏览器得控制台输出window }(this)
方式9,匿名函数前加void
void function(){ console.log(this) // 浏览器得控制台输出window }(this)
方式10,使用new方式,传参
new function(win){ console.log(win) // window }(this)
方式11,使用new,不传参
new function(){ console.log(this) // 这里的this就不是window了 }
方式12,逗号运算符
1, function(){ console.log(this) // window }();
方式13,按位异或运算符
1^function(){ console.log(this) // window }();
方式14,比较运算符
1>function(){ console.log(this) // window }();
最后看看错误的调用方式
function(x,y){ alert(x+y); return x+y; }(3,4);
相关:
http://benalman.com/news/2010/11/immediately-invoked-function-expression
上一篇: 了解 JAVASCRIPT 匿名函数
下一篇: JS:深入理解函数、匿名函数和自执行函数
推荐阅读
-
常用的数据加密和解密方法在JavaScript中
-
在ARM中涉及的函数调用问题进行探讨
-
在JavaScript中获取实时时间、比较时间大小以及进行时间加减运算的方法
-
在JavaScript中实现页面跳转并传递参数的方法
-
搞定!jQuery在JavaScript中绑定事件的多种方法总结
-
在JavaScript中应用外观设计模式的方法
-
Intellij IDEA 插件开发入门详解 - 如何添加 Application 和 Project Component,并创建 Action? 在本文中,我们将详细介绍如何在 IntelliJ IDEA 中添加 Application 和 Project Component,并且通过这些组件来创建一个简单的 Action。 首先,我们将在 src 目录上使用 Alt+Insert 快捷键打开 New 对话框,然后从中选择 Application Component 并输入名称如 MyComponent。接下来,我们在 MyComponent 类中添加一个 sayHello 方法并编写相关逻辑。 然后,我们需要为我们的插件添加一个 Action,使用户可以通过菜单或其它方式访问它。为此,我们将创建一个新的类 SayHelloAction 继承自 AnAction 类,并在 actionPerformed 方法中获取 Application 和 MyComponent 对象,最后调用 MyComponent 的 sayHello 方法。 最后,我们需要为我们的插件配置相关的文件以确保它可以正常运行。在本文中,我们将详细介绍如何进行这些配置。
-
在JavaScript中添加星期和季度到时间格式化:dateFormat的使用方法
-
简易讲解:在JavaScript中添加数组元素的三种方法
-
在JavaScript中向数组添加新项或插入数据的方法