Javascript's Scope Chain

1. Scope concept:

The scope is the code scope of the availability of the variable, which is called the scope of the variable.

2. Scope chain concept:

When you want to access a variable, you will first search in the current scope. If you do not find it in the current scope, you will return to the upper scope to search until you find the global scope. The chain formed by this search process is called a scope chain.

3. The scope is divided into:

  • global scope
  • block scope
  •  function scope ( local scope )

        1.1 Global scope: Any variable that is not declared in a function or in curly braces is in the global scope, and variables declared in the global scope can be accessed anywhere in the program 

// 全局变量
var greeting = 'Hello World!';
function greet() {
  console.log(greeting);
}
// 打印 'Hello World!'
greet();

        1.2 Function scope ( local scope ): If a variable is declared inside a function it is under a function scope. These variables can only be accessed inside the function, not outside the function

function greet() {
  var greeting = 'Hello World!';
  console.log(greeting);
}
// 打印 'Hello World!'
greet();
// 报错: Uncaught ReferenceError: greeting is not defined
console.log(greeting);

It can be seen that the variables or functions declared inside the function in the above code cannot be accessed outside the function, which means that the variables or methods defined inside the function are only in the scope of the function

        1.3 Block-level scope: ES6 introduces letand constkeywords, unlike keywords, variables used and declared varin curly braces exist in block-level scope. These variables cannot be accessed outside of curly bracesletconst

{
  // 块级作用域中的变量
  let greeting = 'Hello World!';
  var lang = 'English';
  console.log(greeting); // Prints 'Hello World!'
}
// 变量 'English'
console.log(lang);
// 报错:Uncaught ReferenceError: greeting is not defined
console.log(greeting);

 

Guess you like

Origin blog.csdn.net/m0_71933813/article/details/129899780