在 JavaScript 中未宣告變數時會發生什麼?
可以的。在全域性作用域下,即使不宣告變數也可以使用。下面的“no 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>
廣告