Problems with js scope

how to interpret the running results of the following two-end code

1

The callback in

an is called bjournal b to print x. Why can"t b get x in a;

let a=fn=>{const x=1;fn();};
let b=()=>{console.log(x)};

a(b);  //Uncaught ReferenceError: x is not defined

2

let a=fn=>{ x=1;fn();};
let b=()=>{console.log(x)};

x;   // Uncaught ReferenceError: x is not defined

a(b); // 1
Mar.28,2021

this problem is mainly about the scope of the arrow function.

The scope of the

arrow function is bound when it is defined.

first question:

  • execute a (b)
  • Define the x variable in the
  • a function and execute b
  • but the scope of the b function has been bound to window,window without x at the time of definition, so an error, x is not defined is reported.

second question:

  • print x, which is because neither of the two functions is executed, so an error, x is not defined is reported.
  • execute a (b)
  • The
  • a function directly assigns a value to x, and since there is no declaration, it is assigned directly to the window object, where window.x = 1.
  • the scope of executing bjournal b is in window, so you can print out x
  • naturally.
The

scope depends on the grammar context. In 1, first of all, there is no definition of variable x in the function scope of b, and then go to the upper layer of the scope chain to find it. This step is critical. The upper layer of the scope chain is the environment in which the'b function definition'is located. We assume that the b function is defined globally, and the upper layer of the b function scope is the global scope. It is obvious that there are no x variables in the global scope. The difference is that in 2, the definition of x does not use keywords, so x is also a global variable (that is, it will be scolded in the project when it is written in demo and interview questions)


variable scope chain is set when you declare variables in the code, and has nothing to do with the position of reading variables at execution time.
when the program executes and reads this variable, it looks for it according to the scope chain set at the time of declaration.


because the places where you declare the function are external, you can only take the outermost variable, and your second x without var or let, is a global variable by default.


the scope of the arrow function

Menu