"use strict" 严格模式是如何被函数继承的?

7

这里是我的代码,似乎表明答案是肯定的 - http://jsfiddle.net/4nKqu/

var Foo = function() {
    'use strict'
    return {
        foo: function() {
            a = 10
            alert('a = ' + a)
        }
    }
}()

try {
    Foo.foo()
} catch (e) {
    alert(e)
}

请问能否引用标准中的声明,说明在应用'use strict'到函数中时,所有嵌套函数和闭包都会自动应用'use strict'


你可能想要在每个函数中明确声明严格模式,否则在代码重构时会留下错误的空间。 - Ingo Bürk
2个回答

8
相关规范部分如下: http://www.ecma-international.org/ecma-262/5.1/#sec-10.1.1 其内容如下:
Code is interpreted as strict mode code in the following situations:
  • Global code is strict global code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.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.

  • 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 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.

因此,在“严格作用域”内明确定义的函数将继承严格模式:

function doSomethingStrict(){
    "use strict";

    // in strict mode

    function innerStrict() {
        // also in strict mode
    }
}
< p >但是,使用< code >Function构造函数创建的函数不会从其上下文中继承严格模式,因此如果您想要在严格模式下使用它们,则必须有一个明确的< code >"use strict";语句。例如,注意< code >eval在严格模式下是保留关键字(但在非严格模式下不是):
"use strict";

var doSomething = new Function("var eval = 'hello'; console.log(eval);");

doSomething(); // this is ok since doSomething doesn't inherit strict mode

2
答案是肯定的,但您可能在文档中找不到完全相同的句子,而是会讲到上下文。 当您在另一个函数Bar内定义函数Foo时,Foo将在Bar的上下文中创建。如果Bar的上下文是严格模式,那么Foo的上下文也处于严格模式。 您可以在这里查看文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode 如果您仔细思考一下,没有这种行为将是非常不实用的(而且没有真正的缺点)。 这对于使整个库在连接多个脚本的情况下无任何问题地使用严格模式也很有帮助:

您还可以采取包装脚本内容的整个内容并使外部函数使用严格模式的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接