This is the third day of my participation in Gwen Challenge

Scope details

To understand scope, you first need to understand several important roles in the running of your program

  • engine

    Responsible for compiling and executing the entire JavaScript program from start to finish

  • The compiler

    Responsible for syntax parsing and code generation

  • scope

    Responsible for collecting and maintaining a series of queries made up of all declared variables and enforcing a very strict set of rules that determine access to these identifiers by currently executing code

Here is a small chestnut to illustrate the connection between the three

var a = 2
Copy the code

Running this line of code does two things: first the compiler declares a variable in the current scope (if it hasn’t been declared before), and then the phase engine looks for the variable in the scope and assigns it a value if it can find it (undefind if it can’t).

Lexical scope and dynamic scope

Lexical scope: The lexical scope is defined at the lexical stage, or rather, the lexical scope is determined by where you write the variable and block scopes as you write the code, so the lexical scope remains the same when the lexical analyzer processes the code.

Dynamic scope: Dynamic scope does not care about how and where functions and scopes are declared, only where they are called, or that the scope chain is based on the call stack rather than the nesting of scopes in the code.

JavaScript uses lexical scope

Function scope

Meaning: All variables belonging to this function can be used and reused throughout the scope of the function

“Hide” variables and functions
function foo(a) {
    var b;
    b = a + bar(a * 2);
    function bar (a) {
        return a + 1;
    }
    return b
}

foo (2)	/ / 7

b 		// undefind
bar()	// undefind

// Internal variables and functions cannot be accessed from global variables
Copy the code
To avoid conflict

Modular scheme

Copy the code
Execute functions now (IIFE)
// Avoid variable contamination
var a = 2;

(function IIFE (glob) {
	var a = 3
	log( a ) / / 3
	log( glob.a ) / / 2}) (window)
Copy the code
// Undedind is overwritten
undefind = true

(function IIFE ( undefind ) {
	var a;
     if (a === undefind) {
         log( "a is undefind")}}) ()Copy the code
// Invert the code order
var a = 2;

(function IIFE ( def ) {
	def (window)
})(function (glob) {
    var a = 3
	log( a ) / / 3
	log( glob.a ) / / 2
})
Copy the code
Block scope
“False” block-level scope
var foo = true
if (foo) {
    var bar = foo * 2
}
console.log('bar', bar)	// The bar can still be accessed. Var declares the same variable wherever it is written. This just looks like block-level scope
Copy the code
Try /catch block scope

Try /catch as defined in ES3 creates block-level scopes

try {
	undefind()
} carch (err) {
	log (err) // Can be executed normally
}

log(err) // err not find
Copy the code
In ES6, let creates block-level scopes