Re: [ js ] 全域和區域變數

看板Ajax作者 (欲翔)時間16年前 (2008/06/17 01:55), 編輯推噓0(007)
留言7則, 1人參與, 最新討論串4/5 (看更多)
函式內的叫區域變數 函式外的叫全域變數 參考資料:w3school、Mozilla 開發者中心 (這兩個夠權威了吧- -) http://www.w3schools.com/js/js_functions.asp The Lifetime of JavaScript Variables When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared. If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed. http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Variables When you declare a variable outside of any function, it is called a global variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within that function. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.122.231.24 ※ 編輯: shyangs 來自: 140.122.231.24 (06/17 01:56)

06/17 05:56, , 1F
如果是用var 宣告的,上面的說法沒問題.
06/17 05:56, 1F

06/17 05:57, , 2F
如果不是用 var 宣告的,就不對.
06/17 05:57, 2F

06/17 05:59, , 3F
權威的 Mozilla 也說 (http://tinyurl.com/njdzw)
06/17 05:59, 3F

06/17 06:00, , 4F
By simply assigning it a value. For example, x = 42
06/17 06:00, 4F

06/17 06:01, , 5F
This always declares a global variable and
06/17 06:01, 5F

06/17 06:01, , 6F
generates a strict JavaScript warning.
06/17 06:01, 6F

06/17 06:02, , 7F
You shouldn't use this variant.
06/17 06:02, 7F
文章代碼(AID): #18LgaLoS (Ajax)
文章代碼(AID): #18LgaLoS (Ajax)