I have been free recently and compiled some little knowledge in JavaScript. For example, in some interview questions, the formal parameters of the function and the variables or functions declared inside the function have the same name. So what is the situation? For those who want to know, continue Read on.
function ab(x){ console.log(x); var x; console.log(x); }; ab(3);
This result occurs, but when the variable declared in the function is assigned a value, the passed in parameter will be replaced.
function ab(x){ console.log(x); var x = 4; console.log(x); }; ab(3);
The output result is: .
When the function declared in the function has the same name as the formal parameter:
function ab(x){ console.log(x); function x(){ console.log("我是函数") }; console.log(x); }; ab(3);
The output result is:
Why is this happening? One of the features of JS is function declaration promotion. This also applies inside the function. That is to say, the function declared in the function body will be promoted to the first position of the function. OK, so when ab is called, x is not 3 as soon as it is passed in.
But the way of assigning anonymous functions to variables does not have the feature of function declaration promotion, so x will not be changed until after the declaration, as shown below ;
The above is the detailed content of In-depth understanding of function parameters and problems when declaring variables or functions with the same name inside a function. For more information, please follow other related articles on the PHP Chinese website!