About functions and closures in JavaScript

Source: Internet
Author: User
In this article, I will talk to you about functions and closures in JavaScript. If you need them, you can refer to the closure, next, let me take a look at the closure.

I. Description of closures

For Functional Languages, functions can save internal data states. For a compiled imperative language like C #, because the code is always executed in the code segment and the code segment is read-only, the data in the function can only be static data. Local variables in a function are stored on the stack. After the function is executed, the occupied stack is released. Therefore, local variables cannot be saved.

Javascript uses lexical scopes. Function execution depends on variable scopes,This scope is determined when defining the function.. Therefore, the function object in Javascript not only saves the code logic, but also must reference the current scope chain. The local variables in the Javascript function can be modified, and the last modified State continues when the function enters the function again. This is because local variables are not stored on the stack, but saved through an object.

The variable used is determined by the scope chain. Each time a function instance is generated, an object is created for it to save local variables, add the object used to save local variables to the scope chain. Different Function objects can be associated through the scope chain. All functions in Javascript are closures, so we cannot avoid "generate" closures.

Reference a diagram in Javascript advanced programming, although this diagram does not fully illustrate all situations. The activation object in the figure is the object used to save the variable.


In short, in Javascript:

Closure: The function instance stores the reference of the variable required for execution, instead of copying and saving the value of the variable at that time. (In the implementation of Object C, we can choose to save the current value or reference)

Scope chain: the way to locate a variable when parsing the variable. use var as the Terminator. If there is no var on the chain, it is traced back to the global object.

The closure feature in C # is implemented by the compiler to convert local variables into object members of the reference type.

Ii. Use of closures

Here are some examples to illustrate how to use the closure feature:

1. closures are generated during definition.

Function Foo () {function A () {} function B () {} function C (){}}
Every time we execute Foo (), there are three function instances (closures), namely, A, B, and C. When Foo is executed, there is no reference to the generated instance, therefore, it will be destroyed as garbage (not necessarily immediately ).
Let's confirm that the scope chain is determined when the function is defined, so the display here should be 'local scope'

Var scope = "global scope"; function checkscope () {var scope = "local scope"; function f () {return scope;} return f;} checkscope ()()


Likewise:

(Function () {function A () {} function B () {} function C (){}}())
After the above expressions are executed, the three function instances A, B, and C (closures) will also be generated, because this is an anonymous function that is executed immediately, and these three closures can only be generated once. The generated closure has no other references, so it will be destroyed as garbage (not necessarily immediately destroyed ).

We write this in two places.

1. Avoid Global Object contamination

2. Avoid multiple function instances

The following two examples show how the closure stores the scope chain:

Function A () {}// saves the amount of memory for writing. It is fast to create objects and has low overhead (function (prototype) {var name = "a"; function sayName () {alert (name);} function ChangeName () {name + = "_ changed"} prototype. sayName = sayName; // reference the closure generated by executing an anonymous function. The closure only produces prototype once. changeName = ChangeName;} (. prototype) var a1 = new A (); var a2 = new ();
A1.sayName (); a1.changeName (); a2.sayName ();


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

Function B () {// The prototype chain is short. The method is fast but memory-consuming, each new call constructor has two function instances and one variable. Var name = "B"; function sayName () {alert (name);} function changeName () {name + = "_ changed";} this. sayName = sayName; // reference the closure. Every time function B is called, a new closure is generated. this. changeName = changeName;} // if the new Keyword exists before the function is called, the function is used as the constructor. // Essentially, it is no different to call a constructor as a common function. If B () is called directly, this object is bound to a global object, and the newly generated closure is assigned to the changeName and sayName attributes of the global object instead of the old closure, therefore, the old closure will be treated as garbage collection. // If used as the constructor, the new keyword will generate a new object (this points to this new object) and initialize the sayName and changeName attributes of the new object, therefore, each generated closure is retained because of reference. Var b1 = new B (); b1.sayName (); b1.changeName (); b1.sayName (); var b2 = new B (); b2.sayName (); b1.sayName ();


Iii. leakage problem: in the compilation language, the function body is always in the code segment of the file and is loaded into the executable memory zone during runtime. In fact, we don't think the function itself has a lifecycle. In most cases, we think that the "referenced data structure" has a life cycle and leakage problems, such as pointers and objects.

Memory leakage in JavaScript is essentially an object generated when the function is defined to save local variables. Because of the reference, it is not recycled as garbage.

1. Circular references exist.

2. Some objects cannot be destroyed, for example, IE6 Memory leakage in DOM, or the Javascript engine cannot be notified during destruction. Therefore, some Javascript closures cannot be destroyed. These situations are usually caused by poor communication between the Javascript Host object and the original Javascript Object.

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.