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,逗號運算子
function(){
console.log(this) // window
}();
方式13,位元異或運算子
^function(){
console.log(this) // window
}();
方式14,比較運算子
function(){
console.log(this) // window
}();
最後看看錯誤的呼叫方式
function(x,y){
alert(x+y);
return x+y;
}(3,4);
匿名函數的N種寫法如下圖
匿名函數沒有實際名字,也沒有指針,怎麼執行?
關於匿名函數寫法,很發散~
+號是讓函數宣告轉換為函數表達式。總結一下
(function() {
alert('water');
})();
(function(o) {
alert(o);
})('water');
(function(o) {
console.log(o);
return arguments.callee;
})('water')('down');
~(function(){
alert('water');
})();//写法有点酷~
void function(){
alert('water');
}();//据说效率最高~
+function(){
alert('water');
}();
-function(){
alert('water');
}();
~function(){
alert('water');
}();
!function(){
alert('water');
}();
(function(){
alert('water');
}());//有点强制执行的味道~