Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

var Hoisting in JavaScript


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...