如果我们使用匿名函数
var FUNCTION_NAME = function(){
/* FUNCTION_BODY */ ;
}
这种方式,编译后变量声明 FUNCTION_NAME 会被提前,但是他的赋值(也就是 FUNCTION_BODY)并不会提前。
也就是说匿名函数只有在调用时才被初始化。
如果我们使用
function FUNCTION_NAME(){
/* FUNCTION_BODY */ ;
}
这种方式,编译后函数声明和他的赋值都会被提前。
也就是说函数声明过程在整个程序执行之前的预处理就完成了,所以只要在同一作用域,就可以访问到,即使在定义之前调用也可以。
比如:
function hereorThere(){
return 'here';
}
alert(hereorThere()); // alert "there"
function(){
return "there";
}
结果会弹出there。主要原因是JavaScript函数声明的“提前”行为。简而言之,就是JavaScript允许我们在变量和函数被声明之前使用它们,而第二个定义覆盖了第一个,相当于:
function hereorThere(){ // function statement
return "here";
}
function hereorThere(){ // 申明前置了,但因为这里申明和赋值在一起,所以一起前置
return "there";
}
alert(hereorThere()); // alert "there"
再看一个例子
var hereorThere = function(){ // function expression
return "here";
};
alert(hereorThere()); // here
hereorThere = function(){
return "there";
}
这段程序编译相当于:
var hereorThere ; // 申明前置了
hereorThere = function(){ // function expression
return "here";
};
alert(hereorThere()); // here
hereorThere = function(){
return "there";
}