To undertake the summary of the previous blog post, this blog post is the use of code + drawing form, combing the function scope and closure of the understanding.
Scope in a function
In JavaScript, objects and functions are also variables.
In JavaScript, scopes are a collection of accessible variables, objects, and functions.
First we declare a function and then declare and assign a variable inside the function:
function fn(){ var x = 3 console.log(x)}fn.call() //3
In the function FN, a scope is created that requires the value of x to be printed, and the function looks for the x inside itself and then hits the result.
What happens when you declare a function inside a function:
function fn(){ var x = 3 // console.log(x) function fn1(){ var x = 4 console.log(x) } fn1.call()}fn.call() //4
The function fn1 creates a sub-scope within the FN scope that prints without using the variable x in FN, but instead uses the variable x in the sub-scope.
If the variable x is not declared in fn1, what will he print?
function fn(){ var x = 3 function fn1(){ console.log(x) } fn1.call()}fn.call() //3
He would look for the X in FN and print it out.
What if this variable does not exist in the function fn scope?
var x = 5function fn(){ function fn1(){ console.log(x) } fn1.call()}fn.call() //5
It can be seen that when a variable (x) in the function scope (FN1) is called, he first looks for the variable in its own scope, and if the variable is not found, the function can access the variable (x) in the upper-level scope (FN), and if the variable is not found, Then this function can access the upper level, the X in the Global scope (window).
Attention
In understanding the scope, we should pay great attention to the problem of variable promotion.
Like what:
function fn(){ function fn1(){ console.log(x) var x = 5 } fn1.call()}fn.call() //undefined
Why did you print out the undefined?
Because this code actually expresses the meaning of this:
function fn(){ function fn1(){ var x console.log(x) x = 5 } fn1.call()}fn.call() //undefined
The variable x just makes the declaration, but it is not assigned, so the print is undefined.
Closed Package
Now that you understand the scope of the function, you can understand the closure.
The sum of "functions" and "variables that can be accessed inside a function" (also called the environment) is a closure.
For example, the picture above:
The function fn1 plus the variable x in the scope of the function fn that he can access is a closure.
A more detailed explanation of closures, you can look at the Hungfang teacher of this article, we fully understand, to learn, can be.
[JavaScript] Functions in JavaScript (2)