2012-01-20 55 views
4

換句話說,爲什麼分號插入失敗,導致下面的代碼被破壞。爲什麼關閉分號會破壞這段代碼?

function Foo() { } 

Foo.prototype.bar = function() { 
    console.log("bar"); 
} // <------------ missing semicolon 

(function() { 
    Foo.prototype.la = function() { 
     console.log("la"); 
    }; 
})(); 

爲什麼是JavaScript解析引擎嘗試要結合Foo.prototype.bar = function() {什麼在我的封閉?有什麼我可以在這封閉關係,這將使這個明智嗎?

我並不是主張用分號插入可以節省您的期望,我只是想知道爲什麼(更有用的版本)上面的代碼在我意外地離開時破壞了。

回答

3

認爲它是這樣的...

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的建議,二元運算符仍然會評估它的左側和右側的操作數,並返回結果,這將被用於分配。

+1

是的 - 所以現在bar並沒有被賦值,而是被這個函數調用的那個函數的結果。謝謝 –

+0

HEH - 我真的認爲我是唯一一個喜歡'+ function()'的人...我認爲唯一的其他人是那些縮小器:) –

+0

@AdamRackis:我們有幾個人在那裏。 :)如果我不關心太多字符,我更喜歡「空白」。似乎更突出。 – 2012-01-20 16:20:32

4

因爲它看到(在下面的橫線,並採取它的意思是你想呼叫以上(使用下面的函數作爲參數)。

+0

*嘆* - 說得好,謝謝。 –