《JavaScript权威指南》:“尽管函数声明语句和函数定义表达式包含相同的函数名,但二者仍不同,函数声明语句中的函数名是个变量名,变量名指向函数对象,和通过var声明变量一样,函数定义语句中的函数被显示地提前到了脚本或函数的顶部,因此它们在整个脚本和函数内都是可见的。使用var的话,只有变量声明提前了,变量的初始化代码仍在原来的位置。”
自己对这段话不怎么理解,于是查了相关资料:
首先要理解:
“A variable with an initialiser is assigned the value of its assignment expression when the variable statement is executed, not when the variable is created.”-----《维基百科》
我的大致理解是:变量的声明只是变量的悬挂,真正的赋值语句执行发生在运行时
接下来:
"variable hoisting---the declaration, but not the initialization, is hoisted to the top of the function. Thirdly, accessing variables before initialization yields undefined
, rather than a syntax error. Fourthly, for function declarations, the declaration and the initialization are both hoisted to the top of the function, unlike for variable initialization. For example, the following code produces a dialog with output undefined, as the local variable declaration is hoisted, shadowing the global variable, but the initialization is not, so the variable is undefined when used"-----《维基百科》
我的大致理解:变量的提升!,变量在一段上下文中无论声明在何处,都会被顶置,但注意,顶置的只有声明而已,由第一点可以知道,此变量仍是undefined,因此前置引用是不可行的。
紧接着:
"Function statements, whose effect is to declare a variable of type Function
and assign a value to it, are similar to variable statements, but in addition to hoisting the declaration, they also hoist the assignment – as if the entire statement appeared at the top of the containing function – and thus forward reference is also possible: the location of a function statement within an enclosing function is irrelevant."----《维基百科》
我的大致理解:函数的提升!,函数也会在一段上下文中被提升顶置,但它与变量提升的最大区别是,它把声明和定义一起提升了,因此前置引用是可以的。
所以,下面的简单例子就可以简单地表达上述的意思
<script type="text/javascript">
fun("hello"); //正确输出
function fun(str){
console.log(str);
}
fun2("hello2"); //错误
var fun2=function(str){
console.log(str);
}
</script>
推荐看的相关博文