我有兩個函數,一個函數調用另一個函數。JavaScript範圍問題:變量未被識別
下面是一個簡單的類比我創建的代碼,其結構我有:
function test1(){
alert(a);//a is not identified here even when test1() is called under test2 which has a defined in scope
alert(b);//b is identified here
}
function test2(){
var a = 'a';//Defining a
test1();//Calling test1()
}
var b = 'b';
test2();
如根據上面的代碼中,函數TEST1()是能夠識別變量b但不變量a。
我的問題是,爲什麼變量a不在test1函數的範圍內,即使我們在test2()中調用test1()時,它定義了變量a?
在此先感謝。
「函數在創建時記住它們的作用域鏈,而不是在它們被調用時。這似乎是整個問題的關鍵。 – netemp