JavaScript closure details, javascript details

Source: Internet
Author: User
Tags closure definition

JavaScript closure details, javascript details

A deep understanding of JavaScript-closures

Like many new users, I am also the frontend. It takes a lot of time and effort to understand closures. The results are also good. Today I will explain the closure in detail based on my own understanding, because there are some detours and confusions when I first started learning, I believe this is also a problem that many people like me will encounter. I will talk about closures with my own learning path and various pitfalls. I hope to help you. (Cainiao, please kindly advise)

What is a closure? As described above in JavaScript advanced programming, closure refers to a function that has the right to access variables in another function scope. The first time I read this sentence, it seems like nothing. If you encounter problems, you will not be able to use them. If you listen to others' analysis headers, you will not understand them. Now I think that to thoroughly understand this sentence, we must have a simple understanding of the JavaScript scope, anonymous functions, and even JavaScript compilation principles. After reading and understanding the explanations of closures in various documents and books, I looked back at some source code and found a little bit of feeling. I think the best sentence to describe a closure is: "A closure is a natural result generated when code is written based on the lexical scope. You do not even need to create a closure to use it intentionally, the creation and use of closures are everywhere in your code. What you lack is to identify, embrace, and influence the thinking environment of closures according to your own wishes ." It's a bit long, but you can understand the actual value of the closure in a language like JavaScript. Next, I will explain the closure in actual examples.

First, let's look at a simple example:

function createComparisonFunction(propertyName){  return function(obj1,obj2){    var value1=object1[propertyName];    var value2=object2[propertyName];    if(value1<value2){      return -1;    }else if(value1>value2){      return 1;    }else{      return 0;    }  } }

In this example, an anonymous function is returned. In the anonymous function, value1 and value2 call the propertyName parameter of the external function createComparisonFunction. Let's look at the definition of closure: a function that has the right to access variables in another function scope. The return anonymous function has the right to access the variable propertyName in the external function scope. Therefore, this is a closure. But in reality, this is just a search rule based on the lexical scope, and it is easy to understand.

Some people may not understand what is the search rule for the lexical scope: in fact, the simple point is to find and obtain the variable based on the variable's function Chain Domain. For the above example, the scope of the createComparisonFunction function includes a variable property and an anonymous function (because no function name is actually not called in the createComparisonFunction function, this is also a disadvantage of the anonymous function, do you remember that the event listening function cannot be removed when calling an anonymous function? The principle is the same.) The scope of an anonymous function includes four variables: obj1, obj2, value1, and value2. When a variable in an anonymous function is called, it is first queried in its own scope. If the variable is found, it is called. If the variable is not found, it is searched for in the outer layer, referenceError will be reported until the global scope is still not found (what if a var a is found? TypeError is reported because a is undefined ). The createComparisonFunction function can only be searched in its scope, but cannot be searched in the inner anonymous function. Such search rules are the Search rules for the lexical scope (of course, this is not just a basic rule ).

Let's look at an example:

function foo() {  var a = 2;  function bar() {    console.log( a );  }  return bar;}var baz = foo();baz();  //2

The answer may be guessed by many people, but what is its implementation principle? I will analyze it in detail now: first, I declare a function foo. Its scope includes the variables a and bar functions. The foo function has a function bar with no new variables. Then define a variable baz whose value is foo () AND foo () returns bar, Gu baz = bar; the last baz () is equivalent to bar (); bar is declared in the foo function according to the lexical scope rule. External access is unavailable! This is the magic of closures! Let's go back to the closure definition again: the function that has the right to access the variable in another function scope. The baz () function has the right to access the bar in the foo function. This is the closure, right! After the closure is clarified, some people will still have questions? How is a closure formed? Why do you say it has the right to access the bar in foo? First, the formation of closures is to create a function within a function, which is the most common method to create a closure. When an internal function is passed outside its lexical scope, it will hold a reference to the original defined scope, and the closure will be used to execute this function.

This is probably the basis of the closure. I hope you can understand it carefully. Take the time to add some other functions of the closure to help you expand your thinking.

Through this article, I hope you can master the knowledge of closures. Thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.