Javascript中定義函數(shù)的方式有多種,函數(shù)直接量就是其中一種碌宴。如var fun = function(){},這里function如果不賦值給fun那么它就是一個匿名函數(shù)。好筒溃,看看匿名函數(shù)的如何被調用恐似。
方式1,調用函數(shù)便锨,得到返回值。強制運算符使函數(shù)調用執(zhí)行
(function(x,y){
alert(x+y);
return x+y;
}(3,4));
方式2我碟,調用函數(shù)放案,得到返回值。強制函數(shù)直接量執(zhí)行再返回一個引用矫俺,引用再去調用執(zhí)行
(function(x,y){
alert(x+y);
return x+y;
})(3,4);
這種方式也是很多庫愛用的調用方式吱殉,如[jQuery](http://jquery.com/),[Mootools](http://mootools.net/)厘托。
方式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,匿名函數(shù)執(zhí)行放在中括號內
[function(){
console.log(this) // 瀏覽器得控制臺輸出window
}(this)]
方式7缎罢,匿名函數(shù)前加typeof
typeof function(){
console.log(this) // 瀏覽器得控制臺輸出window
}(this)
方式8伊群,匿名函數(shù)前加delete
delete function(){
console.log(this) // 瀏覽器得控制臺輸出window
}(this)
方式9,匿名函數(shù)前加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://blog.csdn.net/a454832841/article/details/41940293)谜嫉;