A brief analysis of the priority of the namesake identifier in JavaScript

  • 2020-03-30 00:48:21
  • OfStack

First, the local variables are used before the declaration, do not affect the external variables with the same name


var x = 1; //-> External variable x
function fn(){ 
    alert(x);  //-> Undefined local variable x is used first
    var x = 2; //After declaration and assignment
} 
fn(); 
alert(x); // --> 1<BR> 

The first point, the first sentence of the function fn outputs x, and x is defined in the second sentence. This is allowed in JS, which means that the program can run without syntax errors.

But in other languages, such as C and Java, it is not allowed. Variables must be used after the initial declaration, e.g


public class Test { 
    public static void main(String[] args) { 
        System.out.println(x); //Use the first
        int x = 10; //After the statement
    } 
} 

In Java, the compiler will tell you an error and the program will not run.

Second, the local variable x in fn doesn't affect the external variable x. So the alert output in fn is not 1, it's undefined.

Second, the parameter priority is higher than the function name


function fn(fn){ 
    alert(fn); 
} 
fn('hello'); // --> "hello" 

You can see that the function name and parameter are both fn with the same name, and the output is the string "hello", but not the function body of the function fn (fn.tostring ()).

Three, parameter precedence over arguments


function fn(arguments){ 
    alert(arguments); 
} 
fn('hello'); // --> "hello"<BR> 

The arguments object, which can be used directly within a function, is a special identifier provided by the language itself.

The parameter is just declared to have the same name. You can see that the output is "hello" instead of "[object object]", that is, arguments override the actual arguments provided by the language itself.

Fourth, the parameter has a higher priority than a local variable that is declared but not assigned


function fn(a){ 
    var a; 
    alert(a); 
} 
fn('hello'); // --> "hello" 

The function fn parameter is a, the first sentence in the function only declares the local variable a, but does not assign a value. From the output of "hello" instead of undefined, you can see that parameter a has a higher priority than the declared but unassigned local variable a.

The declared and assigned local variables have a higher priority than the parameters


function fn(a){ 
    var a = 1; 
    alert(a); 
} 
fn('hello'); // --> "1" 

The function fn parameter is a, and the first sentence in the function only declares the local variable a, with a value of 1. From the fact that the output is "1" instead of "hello", you can see that the declared and assigned local variable a has a higher priority than parameter a.


Related articles: