§13.1概括應該是什麼的情況下,如你發生:
- It is a SyntaxError if any Identifier value occurs more than once within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression.
- It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs within a - FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression.
- It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the Identifier of a strict mode FunctionDeclaration or FunctionExpression.
重點煤礦。您的嚴格模式功能的標識符是eval
,因此它是SyntaxError
。遊戲結束。
明白爲什麼上面是一個「嚴格模式的功能表現,」看語義定義在§13(函數定義):
The production
FunctionExpression : function
Identifieropt(
FormalParameterListopt) {
FunctionBody}
is evaluated as follows:
- Return the result of creating a new Function object as specified in 13.2 with parameters specified by FormalParameterListopt and body specified by FunctionBody. Pass in the LexicalEnvironment of the running execution context as the Scope. Pass in true as the Strict flag if the FunctionExpression is contained in strict code or if its FunctionBody is strict code.
重點煤礦。以上顯示了函數表達式(或聲明)如何變得嚴格。它說什麼(用簡單的英語)是一個FunctionExpression有兩種strict
情況:
- 它從
use strict
上下文調用。
- 其功能主體以
use strict
開頭。
你的困惑從思想出現,只有函數體是strict
,而事實上,整個函數表達式是strict
。你的邏輯雖然直觀,但並不是JS的工作方式。
如果您想知道爲什麼ECMAscript以這種方式工作,這很簡單。假設我們有這樣的:
// look ma, I'm not strict
(function eval() {
"use strict";
// evil stuff
eval(); // this is a perfectly legal recursive call, and oh look...
// ... I implicitly redefined eval() in a strict block
// evil stuff
})();
值得慶幸的是,上面的代碼將拋出,因爲整個函數表達式被標記爲strict
。
這裏只是完全猜測,但也許它與這樣的事實有關:在*表達式*中,具有名稱的函數實例化表達式僅在該函數內將該名稱綁定*;換句話說,它在內部就好像有一種'var'聲明創建一個局部變量的魔術方式,該局部變量是通過引用該函數來初始化的。因此,就好像你試圖在本地綁定全局符號「eval」。 – Pointy
@Pointy好提示。我將不得不檢查標準以確定在該場景中到底發生了什麼...... –
只有函數eval()會得到相同的錯誤消息(SyntaxError:函數名稱不能是eval或嚴格模式下的參數) {'嚴格使用'; };' – some