1, the origin of essays
The first day to open a blog to monitor their own study and share a little humble opinion, no accident, should be a Monday more or a week two more.
This blog is written mainly for the front-end work encountered some of the problems and frequently asked questions, on the basis of a little humble opinion, if there are errors, please see everyone can be generous, thanks.
A few days ago in a technical group of water, suddenly a group of friends raised a problem, although not difficult, but it is the ordinary people ignore the point, and more times, so write something here, remind yourself.
var and function in 2,javascript
First, let's take a look at this demo
var f = function () {
Console.log (' 1 ');
};
function f () {
Console.log (' 2 ');
};
f ();//1
When you see this, someone might ask why, shouldn't the output be 2?
Here's a priority issue, in JavaScript (ES5), var and function-defined variables are going to rise, that is, the process of Var and function-defined variables is placed at the top of the scope, and Var takes precedence over function.
In order to confirm the priority of Var and function, we can test 4 simple pieces of code:
First paragraph
var e;
function e () {};
Console.log (typeof e);//function
Second paragraph
function e () {};
var e;
Console.log (typeof e);//function
Third paragraph
var e;
Console.log (typeof e);//undefined
Fourth paragraph
function e () {};
Console.log (typeof e);//function
When it comes to this, some people may ask, why, Var is in front, function is behind, our first code output is 1 instead of 2? Isn't it supposed to be covered by function?
To explain this, the increase in VAR is only responsible for promoting the defined behavior. Let's Read the var one = ' 1 ', which should be 2 behavior var one;one=1;
So, the code above actually looks like this:
var F;
function f () {
Console.log (' 2 ');
};
f = function () {
Console.log (' 1 ');
};
f ();//1
here F points to an anonymous function,function () {Console.log (' 1 ');}; Overrides the previous definition.
The definition of variables in JavaScript can probably refer to the order above, but it is recommended that you define variables in order and follow the order of var > function > Assignment in this scope for reading.
Finally thanks to the screen before you spend valuable time to see this little thing.
A brief talk on the problem of variable promotion in JavaScript