Javascript中匿名函数的多种调用方式
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);
|
这种方式也是很多库爱用的调用方式,如jQuery,Mootools。
方式3,使用void
1
2
3
4
|
void
function
(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);
|
方式6,匿名函数执行放在中括号内
1
2
3
|
[
function
(){
console.log(
this
)
// 浏览器得控制台输出window
}(
this
)]
|
方式7,匿名函数前加typeof
1
2
3
|
typeof
function
(){
console.log(
this
)
// 浏览器得控制台输出window
}(
this
)
|
方式8,匿名函数前加delete
1
2
3
|
delete
function
(){
console.log(
this
)
// 浏览器得控制台输出window
}(
this
)
|
方式9,匿名函数前加void
1
2
3
|
void
function
(){
console.log(
this
)
// 浏览器得控制台输出window
}(
this
)
|
方式10,使用new方式,传参
1
2
3
|
new
function
(win){
console.log(win)
// window
}(
this
)
|
方式11,使用new,不传参
1
2
3
|
new
function
(){
console.log(
this
)
// 这里的this就不是window了
}
|
方式12,逗号运算符
1
2
3
|
1,
function
(){
console.log(
this
)
// window
}();
|
方式13,按位异或运算符
1
2
3
|
1^
function
(){
console.log(
this
)
// window
}();
|
方式14,比较运算符
1
2
3
|
1>
function
(){
console.log(
this
)
// window
}();
|
最后看看错误的调用方式
1
2
3
4
|
function
(x,y){
alert(x+y);
return
x+y;
}(3,4);
|
相关:
分类:
JavaScript
评论
#1楼 2011-02-28 09:28 又见fuckyou
#2楼 2011-02-28 09:34 SeaSunK
#3楼 2011-02-28 09:49 ckd
你应该在讲讲每个例子的内在
#4楼 2011-02-28 10:23 Icebird
#5楼 2011-02-28 10:53 Gray Zhang
#6楼 2011-02-28 13:17 wjp0160
#7楼 2011-02-28 17:15 undefined
不知道其他的有什么好处。
有的甚至没见过。
感觉有2, 足够了。
#8楼 2011-05-05 13:37 老马睡不醒
#9楼 2011-06-07 11:36 在北落
function () {}(function (x, y) {alert(x + y);return x + y;}) is not a function
[在此错误处中断] })(3, 4);
#10楼 2012-06-26 22:14 huajs
!function ($) {
//...
}(window.jQuery);
也能自动执行,这个是新方法吗?
#11楼 2014-09-16 16:30 暖男。
强制函数直接量执行再返回一个引用,引用再去调用执行
什么意思,求解释。说的通俗易懂点
#12楼 2015-04-15 09:51 林Lin☆☆
有个哥们写的这篇文章,你可以看一下,会对你有帮助的.
http://segmentfault.com/a/1190000000327820