我明白var關鍵字意味着裏面的功能,但現在我想明白了什麼是外功能var關鍵字的目的。我做了一些測試(見下文),它沒有區別。那麼,如果你把var關鍵字放在函數外面,它會有什麼區別呢?的javascript使用var關鍵字函數外
1.
example = 1;
function test(){
var example = 2;
}
test();
alert(example); //alert 1 no matter if example=1 or var example=1 before function
2.
example = 1;
function test(){
example = 2;
}
test();
alert(example); //alert 2 no matter if example=1 or var example=1 before function
3.
var example = 1;
function test(){
alert(example);
}
test(); //always alert 1, no matter if var example=1 or example=1 before function
可能重複(http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var- in-javascript)(第一句)。 – 2012-08-08 17:09:30
要特別注意(當前第二個)在該重複問題上的答案 - http://stackoverflow.com/a/1471738/211070 – Tom 2012-08-08 17:14:53