Blog address: Promotion mechanism
A thought triggered by a group discussion
Question: What does the following code output?
var getName = function() {
console.log(1)
}
function getName() {
console.log(2)
}
getName()
Copy the code
At first I thought it would be 2, because the following code overlays the preceding one, but the answer tends to skew away from what we think ε=(´ο ‘*)). After seeing the great god in the group, he mentioned that function promotion is better than variable, so he began to think about the promotion mechanism.
Function promotion is better than variable promotion
There is nothing wrong with this statement, on Page 111 of the Redbook: the parser reads the function declaration first when loading data into the execution environment and makes it available (accessible) before any code is executed. Function declaration promotion is mentioned on page 40 of JavaScript volume 1 over variable promotion. Visible code
console.log(getName)
var getName = 1;
function getName() {
console.log(2)
}
Copy the code
The output is the function getName
Problem to upgrade
Let’s start with the code:
/* * function declarations are superior to variable declarations * function expressions promote variables, but code is assigned at execution time */test(a); console.log(test);
function test() {
console.log(I'm a function.);
}
console.log(test);
var test = 'I'm a variable';
console.log(test);
var test = function (params) {
console.log(I'm a function expression.);
}
console.log(test);
test(a);Copy the code
This time, I added the function expression and the result is as follows:
Another level
This time, I’m going to switch the code order
test(a); console.log(test);
var test = 'I'm a variable';
console.log(test);
var test = function (params) {
console.log(I'm a function expression.);
}
console.log(test);
function test() {
console.log(I'm a function.);
}
console.log(test);
test(a);Copy the code
The results are as follows:
This time I put the function declaration at the bottom, but instead of executing test() for the last time, the output is that I am the function expression. Explanation: the function is already parsed by the parser when it is promoted, and the code is not parsed again when it reaches the function, so it is not assigned again. There is no such thing as overwriting the previous code.
Note: If two functions have the same name, the latter overwrites the former.
console.log(test);
function test() {
console.log(I'm a function.);
}
console.log(test);
function test() {
console.log(I'm a function expression.);
}
console.log(test);
test(a);Copy the code
Results:
At the correct