Home > Web Front-end > JS Tutorial > In-depth understanding of function parameters and problems when declaring variables or functions with the same name inside a function

In-depth understanding of function parameters and problems when declaring variables or functions with the same name inside a function

yulia
Release: 2018-09-19 14:48:07
Original
2131 people have browsed it

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);
Copy after login

In-depth understanding of function parameters and problems when declaring variables or functions with the same name inside a function

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);
Copy after login

The output result is: .

In-depth understanding of function parameters and problems when declaring variables or functions with the same name inside a function

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);
Copy after login

The output result is:

In-depth understanding of function parameters and problems when declaring variables or functions with the same name inside a function

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template