我一直在使用
Object-Oriented JavaScript by Stoyan Stefanov学习Javascript
他提供了一个比较全局和本地范围的示例:
var a = 123; function f() { alert(a); var a = 1; alert(a); } f();
看看这个例子,我预计第一个警报为’123′,第二个警报为’1′.瞧,斯托扬说:
You might expect that the first alert() will display 123 (the value of
the global variable a) and the second will display 1 (the local a).
This is not the case. The first alert will show “undefined”. This is
because inside the function the local scope is more important than the
global scope. So a local variable overwrites any global variable with
the same name. At the time of the first alert() a was not yet defined
(hence the value undefined) but it still existed in the local space.
我的解释并不清楚,局部变量如何在第一个警报中覆盖全局变量?任何其他/不同的解释将不胜感激.