更新时间:2023-12-05 23:38:22
规范的相关部分:
http://www.ecma-international.org/ecma-262/5.1/#sec-10.1.1
其中说:
在以下情况下,
Code is interpreted as strict mode code in the following situations:
如果全局代码以包含使用严格指令(请参见14.1)的指令序言开头,则它是严格的全局代码.
Global code is strict global code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1).
评估代码以包含使用严格指令的指令序言开头或调用eval,则该评估代码为严格的评估代码是对eval函数的直接调用(请参见15.1.2.1.1),即包含在严格模式代码中.
Eval code is strict eval code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct call (see 15.1.2.1.1) to the eval function that is contained in strict mode code.
属于FunctionDeclaration,FunctionExpression或访问器PropertyAssignment的函数代码是严格函数代码,如果其FunctionDeclaration,FunctionExpression或PropertyAssignment包含在严格模式代码中,或者如果函数包含代码以包含使用严格性的指令序言开头指令.
Function code that is part of a FunctionDeclaration, FunctionExpression, or accessor PropertyAssignment is strict function code if its FunctionDeclaration, FunctionExpression, or PropertyAssignment is contained in strict mode code or if the function code begins with a Directive Prologue that contains a Use Strict Directive.
作为最后一个参数提供给内置Function构造函数的函数代码是严格的函数代码,如果最后一个参数是作为FunctionBody处理时以指令开头的字符串包含使用严格指令的序言.
Function code that is supplied as the last argument to the built-in Function constructor is strict function code if the last argument is a String that when processed as a FunctionBody begins with a Directive Prologue that contains a Use Strict Directive.
因此,对于在严格范围"内明确定义的函数,它们将继承严格模式:
So for functions defined explicitly within a 'strict scope', they will inherit strict mode:
function doSomethingStrict(){
"use strict";
// in strict mode
function innerStrict() {
// also in strict mode
}
}
但是使用 Function
构造函数创建的函数不会从其上下文继承严格模式,因此必须具有明确的"use strict";
声明是否要在严格模式下使用.例如,请注意 eval
在严格模式下(但不是在严格模式下)是保留关键字:
But functions created using the Function
constructor don't inherit strict mode from their context, so must have an explicit "use strict";
statement if you want them in strict mode. For example, noting that eval
is a reserved keyword in strict mode (but not outside of strict mode):
"use strict";
var doSomething = new Function("var eval = 'hello'; console.log(eval);");
doSomething(); // this is ok since doSomething doesn't inherit strict mode