Javascript中Function declarations 理解
首先來看一段代碼:
1.f = function() {return true;}; 2.g = function() {return false;}; 3.(function() { 4. if (g() && [] == ![]) { 5. f = function f() {return false;}; 6. function g() {return true;} 7. } 8.})(); 9.console.log(f());
理解上面這段code有幾個關鍵點:
第4行code的理解,if條件中 [] == ![],包括了falsy值,==運算子的邏輯 關於function declarations, if條件中g()
先說答案吧,其實這段code在chrome下返回false,而在firefox下返回true。為什麼有不同的結果呢 ?讓我們且看且分析。
首先,來看 [] == ![] 這句極詭異的比較式的值,這裡是拿一個空數組去跟空數組的取反的值比較,初看起來肯定是false啊。但是,它的值是true。首先我們看右邊的 ![],對一個空數組取反,那麼意味著先要把空數組轉化為一個boolean值,再取反,在javascript中,所有對象在作為boolean值使用時,都是表示true,空數組也是一個對象,所以空數組也是true,那麼對空數組取反,等價於 !true,所以,![]的值為false。
好了,既然右邊說完了是false,現在我們就等於在看 [] == false,剛才不是說了空數組是對象是true麼,那很明顯這個比較就是true == false, 就是返回false對不對?但是不是,這個比較會返回true,有點瘋狂了吧?calm down。根據 ECMAScript的對於==的規範,這樣一個運算式最終是這麼做的
把右邊的false轉成數值0把左邊的對象轉成字串,空數組轉成字串就是Null 字元串把Null 字元串轉成數值,結果是0比較0 == 0,返回true這裡的關鍵是第2步,數組會先轉成Null 字元串,Null 字元其實本身就是一個falsy值。
至於為啥chrome與firefox的行為不一致,在於第6行代碼函數g的聲明在block裡面。
ECMAScript 5, the current official specification of the JavaScript language, does not define the behavior for function declarations inside blocks.
FunctionDeclarations are only allowed to appear in Program or FunctionBody. Syntactically, they can not appear in Block({ ... }) — such as that of if, while or for statements. This is because Blocks can only contain Statements, not SourceElements, which FunctionDeclaration is. If we look at production rules carefully, we can see that the only way Expression is allowed directly within Block is when it is part of ExpressionStatement. However, ExpressionStatement is explicitly defined to not begin with "function" keyword, and this is exactly why FunctionDeclaration cannot appear directly within a Statement or Block (note that Block is merely a list of Statements).
但是依據ECMA6的說法, quoting the ECMAScript 6 draft - B.3.3 Block-Level Function Declarations Web Legacy Compatibility Semantics:
Prior to the Sixth Edition, the ECMAScript specification did not define the occurrence of a FunctionDeclaration as an element of a Block statement’s StatementList. However, support for that form of FunctionDeclaration was an allowable extension and most browser-hosted ECMAScript implementations permitted them. Unfortunately, the semantics of such declarations differ among those implementations. [...]
As ES5 does not define the behavior for function declarations inside blocks while allowing proprietary extensions, there are technically no "rights" or "wrongs". Consider them "unspecified behavior" which is not portable across different ES5-compliant environments.
所以,綜上所述,不要把函數的聲明放到block裡面。切記!!!