Home > Web Front-end > JS Tutorial > body text

JS Closure Essay

舍。
Release: 2017-08-11 14:57:53
Original
1120 people have browsed it

Before starting the formal introduction, let’s look at a more difficult interview question about closures:
function fun(n,o) {
console.log(o)
return {
fun :function(m){
               return fun(m,n); fun(2); a.fun(3);
var b = fun(0).fun(1).fun(2).fun(3);
var c = fun(0).fun (1); c.fun(2); c.fun(3);
//Question: What are the outputs of the three lines a, b, and c?

(Original link: http://www.cnblogs.com/xxcanghai/p/4991870.html)
This question is difficult for everyone to get, especially for novices who do not have a solid foundation. , I was dizzy just looking at it. I roughly explained what this fun function
did (I will analyze this at the end of the article): First, it printed its second parameter, and then returned one Object, this object has a method fun, and then this method re
turns fun(m,n)--the execution result of the outermost function; if you roughly understand the basic process, you can roughly analyze it, but in Before talking about closures, let’s talk about the scope chain of
js:
Every piece of js code (global code or function) (pay attention here, knock on the blackboard!!!) has a scope associated with it scope chain. This
scope chain is an object list or linked list. This group of objects defines the variables in the scope of this code. When js needs to find the value of variable x,
(this process is called ' Variable resolution (varaible resolution)'), it will search from the first object in the chain. If it is not found in the first object, it will
find the next one, and so on.
In the top-level code of js, the scope chain consists of a global object. In a function body that does not contain nesting, there are two objects on the scope chain. The first is the object where the function
defines parameters and local variables, and the second is the global object.

-The content of the above two paragraphs comes from the JS authoritative guide, which is the rhino book
When a function is defined, it actually saves a domain chain. When this function is called, it creates a new object to store its local variables, adds
this object to the saved scope chain, and creates a new, longer one that represents the scope of the function call. chain. For nested functions, every time
the external function is called, the scope chain is different, and the internal function will be redefined again. Each time the external function is called, the code of the internal function is the same, and
The scope chain associated with this code is also different.
-The above content is also from the JS authoritative guide, that is, the rhino book
probably summarizes that each function will form a domain chain. Due to the
sorting relationship of objects on the scope chain, when accessing variables, you can follow one principle - the proximity principle.
After talking about scope, let’s talk about closures.
In short, chaotic scope chain is the culprit of closure.
Let’s take a very simple example:
var d;
function outter(){
var c = 0;
console.log(c);
d = function() { c++; }
                                                                                                                                                              . Generally speaking, every time a js function is called, a new object is created to save local variables, and this object is added to the scope chain. When the function returns, it is removed from the scope chain. This object is deleted. If there are no nested functions and no other references pointing to this bound object, it
will be garbage collected. If nested functions are defined, each nested function will form its own scope chain, and this scope chain points to a variable binding object
. If these nested function objects are saved in the external function, Then they will also be garbage collected like the variable binding objects they point to. But if
these nested functions are returned as return values, or stored in a property somewhere, there will be an external reference pointing to the nested function. It will not be treated as
garbage collection, and the variable binding object pointed to will not be treated as garbage collection!
So in the above code, after calling outter, since the external variable d refers to the nested function, after the execution of outter is completed, the nested
function pointed to by d and the variable binding object it points to are It was not recycled, so c was not recycled, so there is a future story. . .
Let’s give an English explanation of closure (the following is taken from MDN’s explanation):
A closure is the combination of a function and the lexical environment within which that
function was declared.

What's the meaning? The direct translation of the above is: a closure is a combination of a function and the lexical scope environment in which the function is declared.
Let’s talk about the question mentioned at the beginning:

function fun(n,o) {
console.log(o)
return {
fun:function(m) {
                                 return fun(m,n); (3);
Let me explain what will happen when this statement is executed:
fun(0):
fun(0) => n = 0,o = undefined;
console.log(o); => o = undefined;print undefined
return { fun: function(m){ return fun(m,n) } }; => Define nested functions to form a scope chain , and referenced by fun of the returned object's properties
 The fun method of the object:
function(m) => m = 1;
return fun(m,n) => m=1,n=0;
Execute the fun function again:
      fun(n,o) => n=1,o=0;
       console.log(o) => Print 0
                                                                                                => m = undefined,n =1; Same as above, the scope chain is saved
fun(0).fun(1).fun(2):
Still the fun method of the returned object is called:
       function(m) => m=2
                                                                                                                                                                                                                          . ##Then print o is print 1. . .
then
Fun (0) .fun (1) .fun (2) .fun (3);
still called the fun method of returning objects:
Function (m) = & gt; m =3
                                                                                                                                                                                        """"""""""" """" La. . .
            … 
      The last b is to call the fun method that returns the object. When fun is executed, it returns an object, so b is an object with a
attribute whose key is the fun value function. , we generally call this attribute a method.
In fact, the last point is what I want to talk about. If it is necessary to show off skills or conditions, use closures. Avoid closures if you can, because as long as you use
closures, it means that you A space is set aside in the memory that your program may not necessarily use, but other programs cannot use it when the computer is running.
It will undoubtedly have an impact on the performance of the program.

The above is the detailed content of JS Closure Essay. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!