在 JavaScript 中,如果不声明变量会发生什么?


可以。在全局作用域内,可以在不声明变量的情况下使用该变量。以下“无 var”变量“points”将查看作用域链,因为没有使用 var 关键字 −

<html>
   <body>
      <script>
         var rank = 5;
         points = 50;
         marks = 300;
         // Anonymous function
         (function() {
            points = 100; //overwrites global scope points
            var rank = 4; //new rank variable is created in this' function's scope
            var marks = 900;
            document.write(rank+"\r
"); //prints 4             document.write(points+"\r
"); //prints 100             document.write(marks+"\r
"); //prints 900          })();          document.write('<br/>');          document.write('<br/>');          document.write(rank+"\r
"); //prints 5          document.write(points+"\r
"); //prints 100          document.write(marks+"\r
"); //prints 300       </script>    </body> </html>


更新时间:2020-6-13

已浏览 167 次

开启你的 职业生涯

完成课程认证

开始
广告
© . All rights reserved.