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

The most common mistakes in HTML tag writing

We better start paying attention, because HTML Po...

WeChat applet component development: Visual movie seat selection function

Table of contents 1. Introduction 1. Component da...

How to use the Linux more command in Linux common commands

more is one of our most commonly used tools. The ...

Detailed description of HTML table border control

Only show the top border <table frame=above>...

How to install ELK in Docker and implement JSON format log analysis

What is ELK? ELK is a complete set of log collect...

VMware workstation 12 install Ubuntu 14.04 (64 bit)

1. Installation Environment Computer model: Lenov...

MySQL Optimization: InnoDB Optimization

Study plans are easily interrupted and difficult ...

Detailed explanation of JavaScript object conversion to primitive value

Table of contents Object.prototype.valueOf() Obje...

Detailed installation process of Jenkins on Linux

Table of contents 1. Install JDK 2. Install Jenki...

Introduction to installing and configuring JDK under CentOS system

Table of contents Preface Check and uninstall Ope...

Tutorial on upgrading, installing and configuring supervisor on centos6.5

Supervisor Introduction Supervisor is a client/se...

WeChat applet uniapp realizes the left swipe to delete effect (complete code)

WeChat applet uniapp realizes the left swipe to d...

A case study on MySQL optimization

1. Background A sql-killer process is set up on e...