编程语言
首页 > 编程语言> > javascript – “use strict”继承/范围

javascript – “use strict”继承/范围

作者:互联网

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

我只是想知道:

Is doing use strict at //1 is enough or do we have to be explicit at all places like //2 and //3.

解决方法:

strict mode上引用MDN,

To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements.

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

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

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

You can also take the approach of wrapping the entire contents of a script in a function and having that outer function use strict mode. This eliminates the concatenation problem but it means that you have to explicitly export any global variables out of the function scope.

你可以像这样测试一下

'use strict';

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

现在,它会抛出错误,

SyntaxError: Duplicate data property in object literal not allowed in strict mode

但是,当你做这样的事情

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

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

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

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

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

由于封闭函数中使用严格,内部函数也将处于严格模式.因此,内部函数将引发SyntaxError.

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

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

要么

console.log("");

'use strict';

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

不会抛出任何错误.

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

标签:javascript,use-strict
来源: https://codeday.me/bug/20190728/1558779.html