JavaScript closures have two uses: one is to access variables inside the function, and the other is to keep the value of the variable within scope. The function is the only scoped object in JavaScript, so the closure of JavaScript depends on the implementation of the function, and the following two examples make a simple description of the JavaScript closures. 1. There is no strict class in the variable JavaScript inside the Access function, so we use functions to emulate the class. We can emulate a counter class like this, and define a count private variable in it: in JavaScript, a function can access a variable that is defined externally, while the outside cannot access a variable defined inside the function. To access variables defined inside a function, you need to define a closure function in the inner part to achieve the purpose of accessing the internal variables of the function by calling the closure function. In the example above, count is the equivalent of a "private variable", which cannot be accessed outside of the counter function. In counter, increment and get two "closure functions" are also defined, both of which maintain a reference to the counter scope, so that the variable count defined in the counter scope can be accessed. 2. Before the variable scope ecmasceript (ES6), there is no block-level variable in JavaScript (you can use let to define block-level variables in ES6), and variables defined with VAR are global or function-level variables. In the above code, we expect to output the number 0 to 9, and the actual output is 10 times 10. This is because JavaScript has only a function-level scope and no block-level scope. To solve this problem, you need to build a scope for the variable. The solution is as follows: Scenario one: Using closure scheme in loops two: returning a function in an anonymous function the above two schemes are implemented by closures (anonymous functions), and after the external function executes I as a parameter, the e variable in the function has a copy of I. The variable passed into the anonymous function is equivalent to having a closure scope and then getting the result we want.
Headline number/IT transcript
Links: http://toutiao.com/a6305505621249933570/
Source: Headline number (today's headline creation platform)
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
Two examples of JavaScript closures