Confusion with JavaScript scoping
This question already has an answer here:
I find the first example more mysterious...
In the second example, you do not declare a variable a
inside of the function. So when you assign to a
, it targets the a
on the outside. Pretty straight-forward.
In the first example, you declare a variable a
inside of the function, but in an unusual way: By declaring a function called a
. So assigning to a
will use that local "variable".
Two things to take away here:
a) Variable and function declarations are "hoisted" to the top of their scope. While function a(){}
is written near the end, the variable a
to hold it is already created and visible at the top of the scope.
b) Functions can be used as variables as well. You can pass functions around, you can re-assign function definitions. They share the same namespace with other variables.
Its because when you use a declared function
it is hoisted up and turned into a function expression, ie var a = function() {};
This is creating a clash with your a
variable.
You can use Visual-Studio for coding:
Programming the code in a TypeScript-File will enable you to see the variable Types by hovering the variable.
It will also warn you, when you try to apply the numerical-value 10 to the variable "a", that was first declared to be a function. That's what I love about TypeScript, you can get more Information about it here: http://www.typescriptlang.org/
链接地址: http://www.djcxy.com/p/40822.html上一篇: 为什么x在内部范围内未定义?
下一篇: 与JavaScript范围混淆