2017-01-18 42 views
1

據我所知在函數內聲明的變量是局部變量(使用var關鍵字或不)。 如果是這樣,那麼爲什麼這個輸出5?當致電func2時,我不應該得到ReferenceError,因爲只有func1才知道x在函數內部創建全局變量 - 爲什麼這會起作用?

<script> 
    function func1(){ 
     x = 5; 
    } 

    function func2(){ 
     document.write(x); 
    } 

    func1(); 
    func2(); 
</script> 
+1

_ 「的函數內聲明的變量」 _,你沒有做因爲你沒有使用'let'或'var' –

+0

當用'val'聲明時,變量是本地的。否則他們是全球性的。 –

+0

閱讀[JavaScript範圍](https://toddmotto.com/everything-you-wanted-to-know-about-javascript-scope/)。 –

回答

2

Afaik, variables declared inside a function are local variables (using var keyword or not).

聲明函數內部變量是局部的,但你沒有任何聲明的變量。你所擁有的就是所謂的「隱式全球」,它只能在「草率模式」下工作。

MDN

Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.

在嚴格模式下,你的代碼產生一個錯誤:

"use strict"; 
 

 
function func1() { 
 
    x = 5; 
 
} 
 

 
function func2() { 
 
    document.write(x); 
 
} 
 

 
func1(); 
 
func2();

+0

所以實際上有一種方法可以在函數內部創建全局變量。謝謝! – onTheFence

+1

@onTheFence是的,這是可能的,但這是一個非常糟糕的主意。這就是爲什麼它會在嚴格模式下產生錯誤。 – JLRishe

2

那是因爲你沒有把它定義爲

function func1(){ 
    var x = 5; 
} 

這意味着,JS會使用全局變量x不存在,但會在運行FUNC1。

「var」的添加定義了局部範圍func1內的變量。

1
function func1(){ 
    x = 5; 
} 

作爲可變未作用域func1與聲明等效於

var x; // In global scope 
function func1(){ 
    x = 5; 
} 

如果是這種情況,那麼您會遇到控制檯中的錯誤,因爲您正嘗試訪問尚未定義的變量。

function func1(){ 
    var x = 5; 
} 
相關問題