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

时间:2011-07-05 06:36:07

标签: javascript

如果我们的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>

1 个答案:

答案 0 :(得分:20)

您必须将"use strict";(或'use strict';)放在每个脚本(或函数)的顶部以使其严格。在您的示例中,File1.js中的函数是严格的,第二个块也不是。有关详细信息,请参阅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>