preface

A few days ago, I saw a popular article on digging gold “the days when I was an interviewer in Cool Kale”. The author of this article elaborates on what skills you should have as a Web candidate to be more marketable from an interviewer’s perspective.

In the process of comparing myself, I found some problems, maybe understand, but not comprehensive, which is also the reason for the birth of this series of articles.

What is scope

In JavaScript, a scope is a collection of accessible variables, objects, and functions. According to scope scope, it can be divided into Global scope and Local scope.

What is a global scope

A Global scope is a collection of accessible variables, objects, and functions that continue through the declaration cycle of an application. In other words, it can be used anywhere, at any time, as long as it is not deleted or overwritten.

The built-in JavaScript object Window, for example, is a global object with a global scope.

It is easy to create a global object (but be careful not to abuse the global scope, which can affect the performance of the application and can also be overwritten by other users).


/* * Variables, objects, functions created outside a function are global and have global scope * msg1 is a global variable that can be used inside func1
var msg1 = 'hello world'

var func1 = function(){
    console.log(msg1)
}

func1() => hello world

Copy the code

What is a local scope

Tip: Local scopes are also called function scopes

A Local scope is a collection of variables, objects, and functions declared inside a function. A Local scope is valid only in the current context.


/* * Variables, objects, functions created outside a function are global and have global scope * msg1 is a global variable that can be used inside func1
var msg1 = 'hello world'

var func1 = function(){
    /* * All variables, objects, functions created inside functions are local and have local scopes * msg2 is a local variable and can only be used inside func1
    var msg2 = 'hello world !!! '
    console.log(msg2)
}

func1() => hello world !!!

// When we print msg2 inside func1, we are prompted that MSg2 is not declared.
console.log(msg2) => Uncaught ReferenceError: msg2 is not defined

Copy the code

Local scope – variable promotion pit

Consider the following code:

/* * func1 Unexpected result!! *'Judgment begins'Why not say a is not defined *'End of judgment'A is not defined */ var func1 =function(){
    console.log('Judgment begins :' + a)
    
    if(1 === 1){
        var a = 1
        console.log('Decision statement :' + a)
    }
    
    console.log('End of judgment :'+ a)} func1() => Start :undefined end :1Copy the code

In JavaScript, declarations (not assignments) of functions and variables are promoted to the top of the function

Well, beaten. And with that principle, let’s see how this function actually works.

Var func1 = / var func1 = / var func1 = / var func1 = / var func1 = / var func1 =function(){
    var a

    console.log('Judgment begins :' + a)
    
    if(1 === 1){
        a = 1
        console.log('Decision statement :' + a)
    }
    
    console.log('End of judgment :'+ a)} func1() => Start :undefined end :1Copy the code

Therefore, after filling in numerous such pits, predecessors concluded a truth:

Be sure to define variables at the beginning of the function.

Local scope – block level scope

In the early days of JavaScript syntax, there was no block-level scope. After ES6, the const and let keywords were introduced. The introduction of const and let helped us solve the problem of invisibility caused by variable promotion.

Back to our example:

/* * func1 The result of finally being normal *letVariables declared by the keyword are called block-level scopes. * That is, there is no way to access the variable until it has been declared. */ var func1 =function(){
    console.log('Judgment begins :' + a)
    
    if(1 === 1){// useletKeyword declaration variablelet a = 1
        console.log('Decision statement :' + a)
    }
    
    console.log('End of judgment :' + a)
}

func1() 
=> 
Uncaught ReferenceError: a is not defined

Copy the code

The variables declared by the let and const keywords are also local variables, but their scope is not local, but block-level. Its scoped bound variable declares a region that is not affected or used by outsiders.

Grammatically, it’s called a “temporary dead zone.”

Local scope – Lexical scope (closure)

In local scopes, there is also a lexical scope (closure)

/* * This is a typical closure * inside func1, another function is defined to print the string that adds x and y */ var func1 =function(x){
    return function(y){
        console.log(x + ' '+ y)}} /* * Thanks to the rules for defining closures (closures create a context containing all local variables accessible at creation time) * f1 and f2 share the same function definition but have different contexts */ var f1 = func1('hello')
var f2 = func1('HELLO')

f1('world') => hello world
f2('WORLD') => HELLO WORLD

Copy the code

What is a scope chain

To talk about scope, you have to talk about scope chains.

What is a scope chain?

The scope chain consists of a series of variable objects of the current environment and the upper environment, which ensures the ordered access of the current execution environment to the variables and functions that meet the access permissions

In human terms:

When a function executes, there are actually rules that specify how the current function can access privileged variables, objects, and functions.

Let’s understand the scope chain with a bit of code:


/* * Functions have an internal property [[scope]] into which they save themselves and all their parent objects when func1() runs. * func2 of [[scope]] = func2.[[scope]] and func1.[[scope]] and global.[[scope]] * Therefore func2 actually computes func2 func1.[[scope]].msg1 + global.[[scope]].msg */
 
var msg = '0'

var func1 = function(){
    var msg1 = '1'
    
    var func2 = function(){
        var msg2 = '2'
        
        return msg + msg1 + msg2
    }
    
    return func2()
}

func1() => 012

Copy the code

reference

  • JavaScript deep scope chain

series

  • One knowledge point a day