我運行下面的JavaScript:爲什麼嵌套函數範圍的變量給出了不同的錯誤
var foo = function() {
var a = 3,
b = 5;
var bar = function() {
var b = 7,
c = 11;
a += b + c;
console.debug(d);
};
bar();
console.debug(c);
var d = 10;
};
foo();
顯然,d
是不知道嵌套函數bar
和c
不知道外部函數foo
。但在開發工具,當我加載我的網頁,我得到兩個不同的日誌逐一:
undefined
Uncaught ReferenceError: c is not defined
爲什麼是錯誤的兩種情況有什麼不同?在我看來,如果相應的變量不爲他們所知或超出範圍,那麼它們應該拋出簡單的引用錯誤。
因爲'c'在功能範圍內。任何用'var'聲明的東西都不可用。它只在其內部可用。 – epascarello
看看:http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – epascarello
和http://stackoverflow.com/questions/7506844/javascript-function-scoping - 吊裝 – epascarello