The basics of functions and closures in JavaScript

Source: Internet
Author: User
Tags anonymous closure function definition garbage collection

Closure this thing, say difficult also difficult, said not difficult also not difficult, below I to own understanding to say the closure

Explanation of closure

For functional languages, functions can save the internal data state. For a compiled command language like C #, the data in a function can only be static data because the code is always executed in the code snippet and the code snippet is read-only. The local variables inside the function are stored on the stack, and after the function is executed, the stack occupied is freed, so the local variables cannot be saved.

JavaScript takes a lexical scope, and the execution of a function depends on the scope of the variable, which is determined when the function is defined . Therefore, the function object in JavaScript not only holds the code logic, it must also reference the current scope chain. Local variables within a function in JavaScript can be modified, and the last modified state continues when it is entered inside the function again. This is because local variables are saved by an object because they are not stored on the stack.

Deciding which variable to use is determined by the scope chain, and each time a function instance is generated, an object is created to hold the local variable, and the object used to hold the local variable is added to the scope chain. Different function objects can be associated through the scope chain. All functions in JavaScript are closures, and we cannot avoid "generating" closures.

Refer to a diagram in the JavaScript Advanced program design, although this picture does not fully explain all the circumstances. The activation object in the figure is the one used to hold the variable.


In short, in javascript:

Closures: A function instance holds a reference to a variable that is required at execution time, and does not copy the value of the variable that was saved at that time. (In the implementation of object C, we can choose to save the value at that time or refer to it)

Scope chain: The way in which variables are found when the variables are parsed, with Var as the Terminator, and if there is no Var on the chain, it goes back to the global object.

The closure characteristics in C # are implemented by the compiler to convert local variables to object members of reference types.

Second, the use of closures

Here are some specific examples of how to take advantage of the closure feature:

1. Closures are generated at the time of definition

function Foo () {function A () {} function B () {} function C () {}}}
Each time we execute foo (), there is a a,b,c of these three function instances (closures), and when Foo finishes, the generated instance has no other references and is then destroyed as garbage (not necessarily destroyed immediately).
Let's confirm that the scope chain is defined in the function definition, so it should be shown here as ' local scope '

var scope = "Global scope"; function Checkscope () {var scope = ' local scope '; function f () {return scope;} return f;} Checkscope () ()


Same reason:

(function () {function A () {} function B () {} function C () {}} ())
The above expression will also have a,b,c of these three function instances (closures), because this is an anonymous function that executes immediately, and the three closures can only occur once. The resulting closures have no other references and are therefore destroyed as garbage (not necessarily destroyed immediately).

The reason we write this is that we have two

1. Avoid polluting global objects

2. Avoid generating the same function instances multiple times

In contrast to the following two examples, how does a closure store a scope chain:

function A () {}//Compare province memory writing, creating objects faster and overhead (function (prototype) {var name = ' A '; function Sayname () {alert (name);} function ChangeName () {name = = "_changed"} prototype.sayname = sayname;//references a closure that is generated by executing an anonymous function, the closure can only occur once prototype.changename = Changen Ame } (A.prototype)) var a1 = new A (); var a2 = new A ();
A1.sayname (); A1.changename (); A2.sayname ();


--------------------------------------------------------------------------------

function B () {//prototype chain relatively short approach, find the method faster, but more memory consumption, each new call constructor has 2 function instances and a variable generation. var name = "B"; function Sayname () {alert (name);} function ChangeName () {name + "_changed";} this.sayname = sayname;//reference closure, every time Produce new closure this.changename = ChangeName; }//If the function is called with the new keyword, the function is used as a constructor. Essentially, as a constructor and as a normal function call is no different. If you call B () directly, the This object is bound to a global object, and the newly generated closure is assigned to the ChangeName and Sayname properties of the global object instead of the old closure, so the old closure is treated as garbage collection. If used as a constructor, the new keyword generates a fresh object (this points to the new object) and initializes the Sayname and ChangeName properties of the new object, so each resulting closure is retained because of a reference. var B1 = new B (); B1.sayname (); B1.changename (); B1.sayname (); var b2 = new B (); B2.sayname (); B1.sayname ();


Leakage problem: In the compiler language, the function is in the Code section of the file, and is mounted in the runtime to mark the executable memory area. In fact we do not think that the function itself will have a life cycle. In most cases, we consider "reference type data Structures" to have life cycles and leaks, such as pointers, objects, and so on.

Memory leaks in JavaScript are essentially the objects that are generated when a function is defined to hold local variables because they are referenced and are not reclaimed as garbage.

1. There are circular references

2. Some objects cannot be destroyed, such as IE6 memory leaks in the DOM, or the JavaScript engine cannot be notified when they are destroyed, so some JavaScript closures cannot be destroyed. These situations are usually caused by the poor communication between JavaScript host objects and JavaScript native objects.

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.