Closed Package Examples in JS

Preface

Expected, the closure is based on the normal garbage collection process. That is, a function (function scope) is performed, and the variables in which the declared variable will be released, and the garbage collector is recycled. But the closing package uses a trick to let the variables inside the scope, still saved after the function is executed, and is not removed by garbage collection.


MDN definition

javascriptkit

lexical effect The three major features of the closure

1, the function nested function

2, the internal function can access variables of the external function

3, parameters and variables will not be recycled.

Scope chain

In the execution process, first find variables from ourselves If you can’t find it, then the scope where the current function is located (the word method domain) To find it, pay attention to the current state of the variable

The blog of the action domain chain
function Contains this variable on its scope chain, Common constituent closure

Under the case, the closure is mainly for

package data

temporary storage data

  • A typical closure case

Function Car () {var speted = 0 function fn () {speed ++ console.log Speed}} Return Fn} var speedup = car () Speedup () // 1speedup () // 2

When the following code is not executed
   function fn () {speed ++ console.log (speed)} Return Fn 

After the code is executed, the local variable SPEEDs inside the function will be destroyed, and since the global scale Speedup has always exists (unless the current page is turned off, the global variable has always existed), then There is no way to be destroyed within the function of the function, there is something that has been used, this is similar to the browser’s garbage collection mechanism, when we execute Speedup (), he will look for the word method in the function of the function, the function Returns an FN, thus forming a closed bag, simple understanding

  VAR speed = 0Function Fn () {speed ++ console.log (speed)}  
This code forms a closure, if not return fn, the local variable inside the function is destroyed.

We can see how the above code uses the immediate execution statement and immediate execution functions:
  function car () {var speted = 0 function fn () {Speed ​​++ Console.log (speed)} Return Fn} Var Speedup = Car () // 1Function Car () {var Speed ​​= 0 Return Function () {Speed ​​++ Console.log (Speed)} VAR Speedup = Car (SPEED)}} var speedup = car ) // 2Function Car (speed) {ReturnFunction () {speed ++ console.log (speed)}} var speedup = car (3) // 3Function Car () {var speted = arguments [0] returnial () {speed ++ console.log (speed)}} var speedup = Car () // 4Function Car () {var speted = 0 Return Function () {speed ++ console.log (speed)}} // 5 CAR can not write, the anonymous function var speedup = (Function Car (Speed) {Return Function () {Speed ​​++ Console.log (Speed)}}) (3)  
Related cases of closed bag

How much is the following code output? If you want to output 3, how to transform the code?

VAR FNARR = []; for (var i = 0; I
   
Evolution

Suppose only two layers of cycles: VAR FNARR = [] for (var i = 0; i

After the transformation (immediately performing the statement, evolution process)
  < 10; i ++) {
 fnArr[i] = function(){
 return i
 };
}
console.log( fnArr[3]() ) // 10 VAR FNARR = [] for (var i = 0; i 

Package a CarObject

VAR CAR = (function () {var speed = 0; function set (s) {speed = s} function get () {return speed} function speedup ) {SPEED ++} function speeddown () {SPEED -} return {set, speedup: speedup, speeddown: speeddow} () car.set (30) car.get () // 30car. Speedup () car.get () //31car.speeddown () Car.get () // 3
  < 2; i ++) {
 fnArr[i] = (function(j){
 return function(){
 return j
 } 
 })(i)
}
fnArr[3]()
//1
var fnArr = [] 
fnArr[0] = (function(j){
 return function(){
 return j
 } 
 })(0)
}
fnArr[1] = (function(j){
 return function(){
 return j
 } 
 })(1)
}
fnArr[3]()
//2
var a = (function(j){
 return function(){
 return j
 } 
 })(0)
}
var b = (function(j){
 return function(){
 return j
 } 
 })(1)
}
b()
//3
var a = (function(j){
 return function(){
 return j
 } 
 })(0)
}
function fn2(j){
 return function(){
 return j
 }
}
var b = fn2(1)
//4
var a = (function(j){
 return function(){
 return j
 } 
 })(0)
}
function fn2(j){
 return function(){
 return j
 }
 return f
}
var b = fn2(1)
//5
var a = (function(j){
 return function(){
 return j
 } 
 })(0)
}
function fn2(j){
 var j = arguments[0]
 function f(){
 return j
 }
 return f
}
var b = fn2(1) How much is the following code output? How to continue to output 0, 1, 2, 3, 4 

[VAR I = 0; I

  The output is: delayer: 5 (continuous output 5), when performing setTimeout, the code will be hung to the task queue, after the passing is completed, and at this time I = 5, so output DELAYER: 5 (continuous output 5) ) < 10; i ++) {
 fnArr[i] = (function(j){
 return function(){
 return j
 } 
 })(i)
}
console.log( fnArr[3]() ) // 3
var fnArr = []
for (var i = 0; i < 10; i ++) {
 (function(i){
 fnArr[i] = function(){
 return i
 } 
 })(i)
}
console.log( fnArr[3]() ) // 3
var fnArr = []
for (let i = 0; i < 10; i ++) {
 fnArr[i] = function(){
 return i
 } 
}
console.log( fnArr[3]() ) // 3 

FOR (VAR I = 0; I

  or  
FOR (var i = 0; i

What is the following code output?
  <5; i++){
 setTimeout(function(){
 console.log('delayer:' + i )
 }, 0)
} FunctionMakecounter () {var count = 0 Return Function () {Return Count ++}; var counter = makecounter () var counter2 = makecounter (); console.log (counter ()) // 0console.log (counter ()) / / 1console.log (counter2 ()) // 0console.log (counter2 ()) // 1 
complement code, implement an array, name, arbitrary field Sorting

VAR users = [{Name: “John”, AGE: 20, Company: “baidu”}, {name: “pete”, age: 18, Company : “Alibaba”}, {Name: “Ann”, AGE: 19, Company: “}] Users.Sort (BYNAME) Users.Sort (Byfield (‘Company’))

)

Answer
  <5; i++){
 (function(j){
 setTimeout(function(){
 console.log('delayer:' + j )
 }, 0)//1000-1000*j 
 })(i)
} 
Function BYNAME (user1, user2) {return user1.name> user2.name} Function Byage (user1, User2) {return user1.age> user2.age} Function Byfeild (Field) {Return Function (user1, user2) {Return User1 [Field]> User2 [Field]}} User2 [Field]}}

Write an SUM function to implement the following call mode
  <5; i++){
 setTimeout((function(j){
 return function(){
 console.log('delayer:' + j )
 }
 }(i)), 0) 
} Console.log (SUM (1) (2)) // 3console.log (SUM (5) (- 1)) // 4 

Summary
 The above is the full content of this article, I hope this paper has a certain reference value for everyone's learning or work. If you have any questions You can leave a message to communicate, thank you for your support of Tumi Cloud.                      
© Copyright Notice
THE END
Just support it if you like
like0
share
comment Grab the couch

Please log in to comment