Free learning recommendation: javascript video tutorial
##JavaScript Scope and Closure
In JavaScript, if you are not clear about scope and closure, there will be many problems when writing code. Today I will make a summary of scope and closure. .Scope
Scope is mainly divided into global scope and local scope, where local scope is divided into function scope and block-level scope.Global scope
If you define a variable outside curly braces ({}) or a function, then it is a global variable, and its function Domain is the global scope.let a = 1function fun1 () { console.log(a) // 结果:1 function fun2 () { console.log(a) // 结果:1 } fun2()}fun1()console.log(a) // 结果:1
It is worth noting that in the same level scope, when using let or const to declare a variable, the second one with the same name will report an error, and when using var to declare a variable, the previous variable will be overwritten;
Local scope
If you define a variable within a function or braces ({}), it is a variable in the local scope. It can be used in any lower-level scope at that level of scope. used in.function fun1() { let a = 100 console.log(a) // 结果: 100 function fun2 () { console.log(a) // 结果:100 } fun2()}fun1()console.log(a) // 结果: a is not defined
Search for free variables
A variable that is not defined in the current scope but is used is a free variable. What are its execution rules? The free variable is searched up to the upper scope, layer by layer, until it is found. If no global scope is found, the error xx is not defined will be reported.
let a = 100function fun1 () { let a1 = 2 function fun2 () { let a2 = 3 let a = 0 function fun3 () { let a3 = 4 a++ console.log(a + a1 + a2 + a3) // 结果: 10 } fun3() } fun2()}fun1()console.log(a) // 结果: 100
Closure
Closure is applied by scope In special cases, there are two main manifestations: (1) The function is passed as a parameter. (2) The function is returned as the return value./** * 函数作为返回值 */function create () { const a1 = 100 return function () { console.log(a1) }}const fn = create()const a1 = 200fn() // 结果: 100/** * 函数作为参数 */function print (fn) { const a2 = 300 fn()}const a2 = 400function fn1 () { console.log(a2)}print(fn1) // 结果: 400
Practical application scenarios of closures
(1) Hiding data, such as making a simple cache tool (2) Function anti-shake and throttling
Related free learning recommendations: javascript(Video)
The above is the detailed content of Introducing JavaScript scopes and closures. For more information, please follow other related articles on the PHP Chinese website!