Analysis of closure principles in Javascript

Source: Internet
Author: User
Tags closure definition

Let's look at a definition:
Closure
A closure refers to an expression (usually a function) with many variables and an environment bound to these variables. Therefore, these variables are part of the expression.
This shows that the closure in Javascript contains the context function. That is to say, the function is based on its environment, which cannot be exceeded, does it seem familiar to linear algebra?
From another perspective, closures are used to implement oo. In JavaScript, there are no public, private, and protect attribute identifiers like C ++. It is difficult to establish a class. "A class is a data with behaviors, while a closure is a behavior with data". In JavaScript, we use the function definition to replace the class definition, and use the closure to replace the setter/getter method. Please refer to the livecode section: CopyCodeThe Code is as follows: function F1 (){
VaR n = 1;
Function getter (){
Alert (N );
}
Return getter;
}

The n declaration and the getter function constitute a typical closure. The final returned function, that is, the "action" just mentioned, aims to get the value of N, so closure is the act of carrying data.
In addition, I think the closure mentioned by Ruan Yifeng is also very concise: "In my understanding, the closure is a function that can read internal variables of other functions ."
Another more academic explanation:
Http://demo.jb51.net/js/javascript_bibao/index.htm
I hope that you can understand the closure from an academic perspective, because all interpretations and simplification of the closure definition are one-sided interpretations of JavaScript.

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.