[問題] Global variable

看板Ajax作者 (澡蘭香)時間12年前 (2013/10/18 10:30), 編輯推噓0(004)
留言4則, 1人參與, 最新討論串1/1
Assigning Values to Undeclared JavaScript Variables If you assign a value to variable that has not yet been declared, the variable will automatically be declared as a GLOBAL variable. This statement: carname="Volvo"; will declare the variable carname as a global variable , even if it is executed inside a function. 請教一下,這裡的英文是什麼意思呢? 它是指當指派一個值給尚未被宣告的變數的話, 變數自己會變成全域變數嗎? 那請問…這一行 carname="Volvo"; 怎麼沒有var呢 0.0 它用在什麼地方都行嗎?例如在一個函式裡面這樣打的話,它就會變全域變數了? (而且不用打var?) 請多指教~ <(__ __)> -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 61.228.120.35

10/18 12:58, , 1F
簡單來說 用var宣告(範圍內第一次用) 就會被限制
10/18 12:58, 1F

10/18 12:59, , 2F
有效範圍(如果跟外面全域同名就分開了 互不影響)
10/18 12:59, 2F

10/18 12:59, , 3F
如果沒用var宣告(第一次用就直接沒var) 那就會變成全域
10/18 12:59, 3F

10/18 13:00, , 4F
所以寫JS的好習慣是記得先用var 宣告
10/18 13:00, 4F
文章代碼(AID): #1IO9qf3Y (Ajax)
文章代碼(AID): #1IO9qf3Y (Ajax)