本文介绍了“使用严格”继承/范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//Global Scope
"use strict"; //1
function A() {
    "use strict"; //2
    function innerA() {
        "use strict"; //3
    }
}

我只是想知道:


推荐答案

在,

连接严格和非严格的脚本是有问题的。因此,建议您逐个函数启用严格模式。

concatenating strict and non-strict scripts is problematic. It is thus recommended that you enable strict mode on a function-by-function basis.

因此将其置于顶部适用于整个文件。您不必在每个函数中明确提及。

So putting it at the top applies to the entire file. You don't have to explicitly mention that in every function.

注意:使用 use strict 在顶部有自己的问题。在链接的MDN页面中阅读它们。因此,推荐的方法,根据MDN是

Note: Using use strict at the top has its own problems. Read about them in the linked MDN page. So, the recommended approach, as per MDN is






你可以测试一下,像这样


You can test that, like this

'use strict';

(function () {
    return {
        1: 1,
        1: 2
    };
})();

现在,它会抛出错误,

SyntaxError:严格模式下不允许对象文字中的重复数据属性

但是,当你这样做时这样的事情

But, when you do something like this

(function () {
    return {
        1: 1,
        1: 2
    };
})();

(function () {
    'use strict';
    return {
        1: 1,
        1: 2
    };
})();

它只会在第二个函数中失败,而不会在第一个函数中失败。因为,只有第二个函数处于严格模式。

it will fail only in the second function, not in the first function. Because, only the second function is in strict mode.

此外,如果你在一个函数中有一个函数,就像你在问题中所示,

Also, if you had a function within a function, like you have shown in the question,

(function () {
    'use strict';
    (function () {
        return {
            1: 1,
            1: 2
        };
    })();
})();

内部函数也将处于严格模式,因为 use strict 在封闭函数中。因此,内部函数将引发 SyntaxError

the inner function will also be in the strict mode because of the use strict in the enclosing function. So, the inner function will raise a SyntaxError.

但是,如果你在 {} 中的一个块中使用 use strict ,它将没有任何效果,例如,

But, if you use use strict in a block within {}, it will not have any effect, for example,

(function () {
    {
        'use strict';
        return {
            1: 1,
            1: 2
        };
    }
})();

console.log("");

'use strict';

var a = {
    1: 1,
    1: 2
};

不会抛出任何错误。

因此, use strict 应位于函数的开头或文件的开头。只有这样代码才会处于严格模式。

So, use strict should be at the beginning of a function, or at the beginning of a file. Only then the code will be in strict mode.

这篇关于“使用严格”继承/范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:16