When using var
to declare variables, the variable can take on either function or global scope. If var
is used within a function, it has function scope, if var
is used outside of any function, the variable has Global scope.
So, your statement of:
But I also learnt that var has a global scope. Then var show not allow
variable redeclaration.
Is actually, not really accurate because it depends on where var
is used and redeclaration (more correctly known as variable "hiding") is possible in any smaller scope than the first declaration was made.
When declaring with var
, the declaration is hoisted to the top of the scope.
I've written another answer that describes and demonstrates this in detail.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…