在 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>
廣告