First, about reporting errors

ReferenceError: the variable could not be found in scope;

TypeError: Scope resolution succeeded, but an illegal or impossible action was taken on the result.

Second, the process of program compilation

  1. Let’s start with lexical analysis
  2. Lexical analysis: Breaking a string of characters into meaningful (for the language) fragments, called tokens, the parser calls stateful parsing rules to figure out the fragmentsaWhether it should be considered a different token or just part of another token.

  3. Parse to generate an abstract syntax tree
  4. Code generation, which converts abstract syntax trees into executable code

Lexical scope

The lexical analysis phase of the compiler is essentially knowing how and where all identifiers are declared, and predicting how to query them. “The eval (…). The mechanisms of “with” and “with” can trick lexical scopes. Use them with caution!

Function and block scope

1. Functions are the most common unit of scope

2. Variables and functions can belong to any code block (in general, any {.. }), instead of just peripheral functions.

3. Variable and function declarations can be promoted, function expressions can’t

var foo = function() {
	console.log( 2 );
};Copy the code

Five, the closure

A closure is a function that can remember and access its lexical scope even when it executes outside its lexical scope

2. Functions can be passed as values, for example:

function foo() {
	var a = 2;

	function bar() {
		console.log( a );
	}

	returnbar; } var baz = foo(); baz(); // 2 -- Wow, closure!!Copy the code

function foo() {
	var a = 2;

	function baz() {
		console.log( a ); // 2
	}

	bar( baz );
}

functionbar(fn) { fn(); // Look, closure! }Copy the code

3. Whatever method we use to pass an inner function outside its lexical scope, it will maintain a reference to the scope it was originally declared in, and the closure will be invoked whenever we execute it.

var fn;

function foo() {
	var a = 2;

	function baz() { console.log( a ); } fn = baz; // Assign 'baz' to a global variable}function bar() { fn(); // Look, closure! } foo(); bar(); / / 2Copy the code