認爲它是這樣的...
Foo.prototype.bar = function() { // <-- 1. function
console.log("bar");
}(function() { // <-- 2. call the 1. function, passing a function argument
Foo.prototype.la = function() {
console.log("la");
};
})(); // <-- 3. tries to invoke the return value of the 1. function,
// but "undefined" was returned.
我不喜歡使用()
爲IIFE。我更喜歡其他運營商。
Foo.prototype.bar = function() {
console.log("bar");
}
void function() {
Foo.prototype.la = function() {
console.log("la");
};
}();
如果我們回到原來的位置,並讓第一個函數返回一個函數,您會看到一個函數被調用。
Foo.prototype.bar = function() { // <-- 1. function
console.log("bar");
return function() { alert('INVOKED'); }; // 2. return a function
}(function() { // <-- 3. call the 1. function, passing a function argument
Foo.prototype.la = function() {
console.log("la");
};
})(); // <-- 4. tries to invoke the return value of the 1. function,
// which will now call the returned function with the "alert()"
更新,可使用一元運算符由@Lasse Reichstein的建議,二元運算符仍然會評估它的左側和右側的操作數,並返回結果,這將被用於分配。
是的 - 所以現在bar並沒有被賦值,而是被這個函數調用的那個函數的結果。謝謝 –
HEH - 我真的認爲我是唯一一個喜歡'+ function()'的人...我認爲唯一的其他人是那些縮小器:) –
@AdamRackis:我們有幾個人在那裏。 :)如果我不關心太多字符,我更喜歡「空白」。似乎更突出。 – 2012-01-20 16:20:32