The content of this article is about the analysis of the difference between JavaScript function declaration and variable declaration. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Today, another question triggered a battle between me and the basics of JS: First of all,
var getName = function(){alert(1)}; function getName(){alert(2)}; getName();// 1
or
function getName(){alert(2)}; var getName = function(){alert(1)}; getName();// 1
Why did I change the order of declarations, but the result was still output? The value of a function declared in the form var
?
Someone answered me and said, "Ah, the variables are improved...", My initial understanding is that even if the variables are improved, after the first situation is improved, it should be like this:
var getName; getName = function(){alert(1)}; function getName(){alert(2)};
The final output should be 2 (very reasonable).
As everyone knows, not only var
declarations will be advanced, functions declared in the form of function fn(){}
will be promoted to the scope. The most is at the top, and then the variable is raised.
Please see the following example for details:
fn();//Uncaught TypeError: fn is not a function var fn = function(){console.log(1)};
but
fn();//2 var fn = function(){console.log(1)}; function fn(){console.log(2)}
It is enough to show that the function is improved more fiercely.
Related recommendations:
javascript variable declaration example analysis_javascript skills
##JavaScript global variable declaration and introduction to advantages and disadvantages
The above is the detailed content of Analysis of the difference between JavaScript function declaration and variable declaration. For more information, please follow other related articles on the PHP Chinese website!