【问题标题】:Do we need to put "use strict" in external js files if our html file already has "use strict"?如果我们的 html 文件已经有“use strict”,我们是否需要在外部 js 文件中添加“use strict”?
【发布时间】:2011-07-05 06:36:06
【问题描述】:

如果我们的 html 文件(导入外部 js 文件)已经有“use strict”,是否需要在外部 js 文件中加上“use strict”?

如果我们的外部 js 文件没有“use strict”,那么它们在具有“use strict”的 HTML 文件中是否仍然“严格”?

例子:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script>
        "use strict";
        function f() {
            // calling File1 functions (File1 does not have "use strict"; at the top)
            // are the File1 functions "strict"?
        }
    </script>
    <script src="File1.js"></script>
    <script>
        //by the way.. is it strict here ?
    </script>
</head>
<body>
</body>
</html>

【问题讨论】:

  • 为什么不呢?您是否担心 15 个字节左右?
  • 你完全误解了我的问题
  • 呃,我的评论试图探究为什么你甚至需要知道。在任何地方都使用严格以使其更便携。 15 个字节左右不会杀死你,所以为了清楚起见,使用它。

标签: javascript


【解决方案1】:

您必须将"use strict";(或'use strict';)放在每个脚本(或函数)的顶部以使其严格。在您的示例中,File1.js 中的函数将 not 严格,第二个块也不会。详情请见https://developer.mozilla.org/en/JavaScript/Strict_mode#Invoking_strict_mode

如果不是这种情况,使用严格模式可能会使您导入的第三方脚本无效,因此严格只适用于您明确指定的脚本和单个函数是有道理的。

例如:

external.js:

console.log("C: This script is non-strict.");

var g = function (x) {
    console.log("g is non-strict regardless of caller.");
    return 2 * x;
};

test.html:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script>
        "use strict";
        console.log("A: This script element is strict.");
        function f() {
            console.log("The strictness of a script does not affect" +
                    " the strictness of external scripts, so g is" +
                    " still non-strict when called from f.");
            return g(3);
        }
    </script>
    <script src="external.js"></script>
    <script>
        f();
        console.log("B: This script element is non-strict.")
    </script>
</head>
<body>
</body>
</html>

【讨论】:

  • 你的意思是如果一个外部的.js文件有“use strict”;就在它的最上面,即使导入的html文件没有使用严格,当外部.js文件中的函数运行时,它们是“严格的”?
  • @KJelly:是的,如果外部JS文件顶部有"use strict";,不管调用者是否严格,都会严格。
猜你喜欢
  • 2014-04-28
  • 2015-05-29
  • 2021-05-16
  • 2020-12-07
  • 2023-03-10
  • 2014-02-17
  • 2016-02-22
  • 2011-07-10
  • 1970-01-01
相关资源
最近更新 更多