簡體   English   中英

foo()和function()之間的區別{foo(); }

[英]Difference between foo() and function() { foo(); }

使用匿名函數包裝函數有什么好處嗎? 我的意思是一個特例:

function asyncFuntion(callback) {
    setTimeout(callback, 6000);
};

asyncFuntion(function() {
    console.log('Calling after 6 s.');
});   

以及包裝功能:

function asyncFuntion(callback) {
    setTimeout(function() {
        callback();
    }, 6000);
};

asyncFuntion(function() {
    console.log('Calling after 6 s.');
});

在這兩種情況下輸出都是相同的。 那有什么區別嗎? 第二個版本是我發現的學習js。 我知道當我們需要閉包時這樣的表格很有用但是在這里?

第二種形式允許您將參數傳遞給callback ,而第一種形式則不允許。

// 1st form
setTimeout(callback("This doesn't work as you might expect"), 6000);

// 2nd form
setTimeout(function() {
    callback("This works");
}, 6000);

如果你沒有傳遞參數,那么包裝函數沒有任何優勢。


為了更加徹底, Function.prototype.bind可以幫助我們使用第一種形式:

 setTimeout(callback.bind(this, "This works fine too"), 6000); // Even with Richard JP Le Guen's example by specifying the thisObj setTimeout(customObj.alert.bind(customObj), 6000); 

但是,您需要將此方法提供給不支持該事件的瀏覽器(即Opera,Safari和IE 8,7,6)。 可以在MDN文檔頁面上找到用於填充方法的代碼。

在匿名函數中包裝函數可以避免使用this關鍵字的復雜性。 在quirksmode上閱讀它們

例如:

function CustomObject() {
    this.msg = "Hello world from my custom object";
    this.alert = function() {
        alert(this.msg);
    };
}

var customObj = new CustomObject();

setTimeout(customObj.alert, 1000); // the alert message says `undefined`
setTimeout(function() {
    customObj.alert();
}, 2000); // the alert message says "Hello world from my custom object"

在匿名函數中包裝函數也是在JavaScript中使用閉包的關鍵:

var arr = ['a','b','c','d','e'];

// will always alert undefined
for(var i=0; i<arr.length; i++) {
    setTimeout(function() {
        console.log(arr[i]);
    }, 1000*i);
}

// outputs the values of `arr`
for(var j=0; j<arr.length; j++) {
    setTimeout((function(indx) {
        return function() {
            console.log(arr[indx]);
        }
    }(j)), 1000*j);
}

如果您需要具有單獨的標識,則環繞非常有用。

var x = function () { cleanup(); };
var y = function () { cleanup(); };
if (x === y) ... // not true

例如,某些函數(如addEventListener對identity進行操作。

element.addEventListener("myEvent", beep, false);
element.addEventListener("myEvent", beep, false);

第二次調用addEventListener ,它說“我已經beepbeep ;我不需要添加另一個。” 觸發myEvent事件時,只會發出一聲嘟嘟聲。 如果您想要發出兩聲嘟嘟聲,則需要確保回調不同。

element.addEventListener("myEvent", function() { beep(); }, false);
element.addEventListener("myEvent", function() { beep(); }, false);

每個匿名函數都不同,所以這次你注冊了兩個函數(碰巧做同樣的事情)。 現在它會發出兩聲嗶嗶聲。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM