JavaScript Basics: Scope

JavaScript Basics: Scope

Before talking about AO and BO, we need to understand the concept of scope, which will make it easier to understand many things later, such as what this points to.

Scope

Scope is simply the scope in which variables, functions, and objects are available after they are defined.

console.log(a)
{
    var a=1;
}
function test(){
     var b=2;
}

insert image description here

It can be seen that variable b cannot be used outside. It can be seen that the scope can protect data from being arbitrarily accessed and modified by the outside world. It can be easily seen that scopes can isolate each other's variables, that is, variables with the same name in different scopes will not conflict.

The most important and commonly used scopes are global scope and function scope. However, after ES6, a block-level scope was introduced due to the emergence of let and const keywords.

Global Scope

Simply put, the global scope means that all domains can access variables and method objects under the scope.

var a="global1";
 function test(){
    b="Without var, it is implicitly converted to a global variable";
    window.c="Directly setting variable c as window will also make it global";
    var d="non-global scope";
 }
 #The first step is to execute test()
test() #This will define and assign values ​​to variables within the method #Step 2 console.log(a)
console.log(b)
console.log(c)
console.log(d)

insert image description here

Generally speaking, the properties of window are global variables, and the window.c format actually treats c as a property of window. Please note that when declaring variables, do not use var. It is better to use var so that it will not be promoted to a global variable, causing data to be contaminated.

In addition, the test method is also a global method.

function test(){
    var a = function(){
        console.log("literal method")
    }
    b = function(){
        console.log("method without var literal")
    } 
   function test1(){
       console.log("normal declaration method")
   }
     
}
 

insert image description here

This shows that the literal declaration method is similar to assigning a function to a variable and treating it as a variable. This was also demonstrated during precompilation.

Function Scope

Function scope is the opposite of global scope. It is not used everywhere, but only in a certain range. Generally, declared variables are only used inside the function.

function test(){
     var a="non-global scope";
     console.log(a)
}

Now there is another problem. Variables within the function scope can be used in the global method. So can a function have a function scope generated by the function below it? And whether their variables can be used interchangeably?

function test(){
     var a="test method scope";
    function test1(){
         var b="test1 method scope";
        console.log("value of a=",a);
    }
    # Call the function inside the function test1();
     console.log("value of b=",b);
 }

insert image description here

It can be seen here that the scope is layered. The inner scope can access the variables of the outer scope, but the outer scope cannot access the inner variables.

if, switch, for, while

Conditional statements and logical loops are not functions and do not behave like functions, nor do they create a new scope. **Variables whose blocks are defined will remain in the scope in which they exist.

function test(a){
    if(a>1){
        var b=13;
    }else{
       var b=1;  
    }
    console.log(b);
}

insert image description here

So when using conditional statements and logical loops, try not to use them in the global scope. Because the variables in its method body will affect other data.

Block Scope

The appearance of block scope generally requires one of the two keywords let or const, otherwise the block scope will not exist.

insert image description here

function test(a){
    const b="23";
    if (a>2){
        const c=3
        console.log("first person if---c-----",c)
    }
    if (a>1){
        console.log("Second person if----b----",b)
        console.log("Second person if----c----",c)
    }
     
}

insert image description here

It can be seen that if there are keywords let and const, the scope of the variable is within the pair of curly braces in which it is declared. Therefore, the c variable in the first if cannot be obtained in the second if. Of course, it still follows that the inner scope can access the variables of the outer scope.

To learn more about let and const, see the previous article: Address

Scope Chain

This seemingly magical concept can be simply described as: if it exists within the scope, it will be used directly, and if it does not exist in the next level, it will be terminated when the global scope is found.

var a=1
var b=3
function test(){
    var a=2
    console.log("value of a",a);
    console.log("value of b",b);
}
 

insert image description here

By the way, the search logic of the scope chain is actually the same as that of the prototype chain. We will continue to talk about it later.

Summarize

This article ends here. I hope it can be helpful to you. I also hope that you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • JavaScript ES new feature block scope
  • JavaScript Advanced Programming: Variables and Scope
  • Graphical explanation of the underlying principle of JavaScript scope chain
  • JavaScript static scope and dynamic scope explained with examples
  • Javascript scope and closure details
  • JS Difficulties Synchronous and Asynchronous and Scope and Closure and Detailed Explanation of Prototype and Prototype Chain
  • A brief discussion on JavaScript scope

<<:  css3 animation ball rolling js control animation pause

>>:  Steps for importing tens of millions of data into MySQL using .Net Core

Recommend

Five practical tips for web form design

1. Mobile selection of form text input: In the te...

Vue+element implements drop-down menu with local search function example

need: The backend returns an array object, which ...

Three principles of efficient navigation design that web designers must know

Designing navigation for a website is like laying...

Case analysis of several MySQL update operations

Table of contents Case Study Update account balan...

CocosCreator implements skill cooling effect

CocosCreator realizes skill CD effect There are s...

Some issues we should pay attention to when designing a web page

Web design, according to personal preferences and ...

Problems and solutions of using jsx syntax in React-vscode

Problem Description After installing the plugin E...

When to use table and when to use CSS (experience sharing)

The main text page of TW used to have a width of 8...

Example of how to implement keepalived+nginx high availability

1. Introduction to keepalived Keepalived was orig...

Use Grafana+Prometheus to monitor MySQL service performance

Prometheus (also called Prometheus) official webs...

Detailed explanation of how to configure openGauss database in docker

For Windows User Using openGauss in Docker Pull t...

How to enable MySQL remote connection

For security reasons, MySql-Server only allows th...