preface

  • In javascript, there is a feature called scope. It is also a prerequisite for understanding closures, and this article focuses on understanding scopes so that in the next article, you can learn and understand closures.

Scope (Scope)

What is the scope?

  • Scope refers to the area in the program where variables are defined. This location determines the lifetime of variables (related to function scope and block-level scope). Popularly understood, scope is the accessible scope of variables and functions, that is, the scope controls the visibility and life cycle of variables and functions. Scope is divided into global scope, function scope and block-level scope.

1. Global scope

  • An HTML page is a global scope. When the page is opened, the scope is generated. When the page is closed, the global scope is closed. Objects that can be accessed from anywhere have global scope. Variables defined outside a function are global variables and have global scope. In addition, the properties of window also have global scope.

For example, in the following code, I exists in the global scope.

var i = 1;
function fun() {
  console.log(i);
}
fun()/ / output 1
Copy the code

At this point, an interesting question popped into my mind: how do you reference the global scope to variables across pages without committing via get/post, etc.? After asking the teacher for advice, I finally got the result I wanted. Write in the script block of an HTML file

    var name = 'wang';
    window.localStorage.setItem('username',name)// Local storage
Copy the code

Open the browser console and enter name to get the following picture. Close the current HTML window

In another HTML filescriptWrite down in

    var name = localStorage.getItem('username');
    console.log(name);/ / wang
Copy the code

Open the browser console to get the following image

The above example makes use of local storage and can reference variables across pages.

2. Function scope

JavaScript you Don’t Know describes function scope like this:

1. Function scope means that all variables belonging to a function can be used and reused throughout the scope of the function (in fact, nested scopes can also be used). 2. The outer scope cannot access anything inside the wrapper function.

Let’s start with an example

function foo(a) {
  var b = 2;
  console.log(b);
  console.log(a);
  function bar() {
    var c = 3;
    console.log(a);
    console.log(b);
    console.log(c);
  }
  bar()
}
// console.log(a,b,c); // All three fail
// console.log(b); //b is not defined
// bar()// bar is not defined 
/ / / foo (1) / 2,1,1,2,3
Copy the code
  • According to the above results, a, B, C and bar are all infoo(..)Inside the function, you can’t go fromfoo(..)External access, that is, not accessible from the global scope. But these identifiers are infoo(..)The interior is accessible, also inbar(..)Internal access is also available (suppose inbarThere is no internal identifier declaration of the same name).

From this we can conclude:

  1. The outer scope cannot access anything inside the wrapper function.
  2. For a nested scope, the inner scope can access the contents of the outer scope.

Function scoped functions

  1. Hide internal implementation
  • “Hide the internal implementation” is written in the code from the selection of an arbitrary fragments, and then use function declarations for packaging, these code “hidden” rise, that is to say, this code for any statement (variable or function) will be bound in the scope of this newly created packaging function, rather than in previous scope.
  • If all variables and functions are in the global scope, it exposes too many variables or functions that are supposed to be private. The correct code should prevent access to these variables or functions.
  • case
    function doSomething(a) {
      b = a + doSomethingElse(a * 2);
      console.log(b * 3);
    }
    function doSomethingElse(a) {
      return a - 1;
    }
    var b;
    doSomething(2);/ / 15
    Copy the code

    In the code snippet,bdoSomethingElse(..)It should bedoSomething(..)Internal concrete implementation of “private” content. In the outer scope pairbdoSomethingElse(..)Not only is “access” unnecessary, it’s dangerous. The hidden Internal implementation allows you to “reasonably” hide these private variables indoSomething(..)Inside, for example

    function doSomething(a) {
      function doSomethingElse(a) {
        return a - 1;
      }
      var b;
      b = a + doSomethingElse(a * 2);
      console.log(b * 3);
    }
    doSomething(2);/ / 15
    Copy the code
  1. To avoid conflict
  • Let’s start with an example
function foo() {
  function bar(a) {
    i = 3;Var I = 3; , which changes I in the scope to which the for loop belongs
    console.log(a + i);
  }
  for (var i = 0; i < 10; i++){
    bar(i * 2);// Infinite loop
  }
}
foo();
Copy the code
  1. bar(..)Internal assignment expressioni = 3Overrides the statement infoo(..)Inside the for loopiTo makeiIt’s always set to 3, and it’s always less than 10.
  2. If you havebar(..)Within thei = 3Set tovar i = 3Variables of the same name or set tovar j = 3With different named variables, you can avoid errors. The reason for this is that,var i = 3forbar(..)Declare a local variable in scope. If the local variable name is still I, you can also call it a “Shadowed variable.”

3. Block level scope

  • Although function scopes are the most common scope units, other types of scope units exist, and even better maintainable, cleaner code can be achieved by using them.

Before introducing block-level scope, let’s do a little experiment with var and let

Let circumstances

{
  let i = 1;
}
console.log(i);//i is not defined
Copy the code

Var cases

{
  var c = 2;
}
console.log(c);/ / 2
Copy the code

It is the same to declare a variable and put it in with {}. Variables declared with let and var have completely different effects outside of {}.

Next, we move into block-level scoping with questions.

Block-level scope is explained in Javascript you Don’t know:

The block scope is a tool used to extend the previous rule of least authorization, extending code from hiding information in functions to hiding information in blocks.

Let’s consider the previous question again, why let declared variable I wrapped in {}, the global scope call I error, I is not defined?

  • The reason is thatiIn the block-level scope, when you are runningconsole.log(i)When,iHas ended his running time.

Then the question arises, why is the variable I defined by var successfully defined?

  • In fact,letCan be understood as more perfectvar.varThe scope of the declared variable is the entire enclosing function. whileletThe scope of the declared variable is only the outer block, not the entire outer function.

With that in mind, let is used to understand block-level scope

  • letA keyword can bind a variable to any scope it is in. In other words,letA variable declared for it implicitly hijacks its block scope.

Then, the concept of block-level scope comes to mind:

  • Block-level scope is designed to keep variable declarations close to where they are used, to maximize localization, and to prevent one variable from contaminating the entire function scope or global scope.

How do I create a block-level scope

Here are a few examples

let

  • The let keyword can change a variable to any scope it is in (usually {.. } inside), in other words, a let implicitly hijacks its scope for the variables it declares.

With the keyword

  • Scopes created from objects with with are only in the WITH declaration and not in the outer scope

try/catch

  • The catch clause of try/catch creates a block scope in which declared variables are valid only inside the catch.

conclusion

  1. Scope is the area in a program where variables are defined.
  2. There are three types of scopes: global, function, and block-level.
  3. Variables defined outside a function are global variables and have global scope
  4. The meaning of function scope is that all variables belonging to this function can be used and reused throughout the scope of the function (and in fact within nested scopes). The outer scope cannot access anything inside the wrapped function.
  5. Block-level scope is designed to keep variable declarations close to where they are used, to maximize localization, and to prevent one variable from contaminating the entire function scope or global scope. You can create block-level scopes with keywords such as let.

Note: this article is a blogger learning JS knowledge, there are mistakes are inevitable, and there are many points of knowledge did not explain clear, welcome big guy correction, I will regularly update the new article and modify the previous mistakes, welcome to the comment area together to discuss learning ~