为什么一个变量在脚本标记内的函数中没有声明't给出错误“;变量未定义”;

Why a variable when not declared in a function inside script tag doesn't give error "variable not defined"

本文关键字:变量 声明 错误 出错 未定义 函数 一个 脚本 为什么      更新时间:2023-09-26

例如:

<!DOCTYPE html>
<html>
<head>
    <title>TEST PAGE</title>
    <script type="text/javascript">
      "use strict";
      function a () {
        i = 0;
      }
   </script>
<body>
   <div> TEST </div>
</body>
</html>

为什么在启用strict mode的情况下,在浏览器中执行此html页面时不会产生"未定义变量"错误?

因为您从不执行a函数。

"use strict"定义JavaScript代码应在"严格模式"下执行严格模式在编译时不起作用。这就是为什么当你的函数被执行但你没有执行它时,它只会显示错误。