Understanding function Scopes and closures

Source: Internet
Author: User

Objective

Whenever reading, or learning a technology, you have to ask yourself the following questions.

    • What is it?
    • What's the use of it? /invented it to solve what problem?
    • What is the disadvantage of it?

I'm going to try to explain the concept of closures in these directions.

Concept

Before we know about closures, we need to understand a few concepts. This article is only a brief introduction here, if you need further information, please refer to the link at the end of the article.

Scope

The scope of variables and functions can be divided into local scope and global scope. JavaScript does not have a block-level scope, but has a function scope.

Execution Environment (Execuation context)

Variables and functions have access to other data.

Execution Environment Stack (execuation context stack)

Each function, when executed, pushes its execution environment into a stack and executes the environment out of the stack and is destroyed after the function is executed. All functions stored therein and the definition of the variable are destroyed, and control is returned to the previous execution environment. The global execution environment will not be destroyed until the application exits (browser close).

Scope chain (scope chain)

Scope chains are used to guarantee orderly access to variables and functions that the execution environment has access to.

What is a closure package?

The concept of closures, which is common in functional programming, is simply to make internal functions accessible to variables defined in external functions. The strict definition is

Declare another function within the function, and return the function. This returned function and its execution environment as a whole are called closures.

Let's look at an example:

function F1 () {  var val = ten;} Console.log (val);     // uncaught referenceerror:val is not defined (...)

The error was reported because the variable inside the function could not be accessed from outside the function. So how can you access variables that are local to the scope?

function F1 () {  var val = ten;   function F2 () {    console.log (val);  }   return closure;} var f2 = F1 (); F2 ();            // Ten

In this code, theF2 function and its execution environment make up an entire closure. For the General F1 () method, the variable val inside it should be garbage collected after the F1 () method has been executed. But F1 () returned a new method, F2 (). Because F2 () accesses the variable val of its external function,val forms the execution environment for the F2 function. Val exists in the scope chain of the F2 , as long as the F2 () method is not destroyed, the variables and functions in its scope chain are not destroyed, and Val is always there.

What's the use of closures? Problems with the For loop variable not being persisted
 for (var i = 0; i < 5; i++) {  setTimeout(function  () {    console.log (i);   5);}

The code block above will print five 5 , and we expect the result to print 1 2 3 4 5.

This is because I in setTimeout is a reference to the external layer I. When SetTimeout's code is interpreted, the runtime simply records the reference to I, not the value. When the setTimeout is triggered, I in the five setTimeout are also valued, since they all point to the same I of the outer layer, and the value of that I is 5 at the completion of the iteration, so it is printed five times 5 .

To get the results we expect, we can assign I to a local variable to get rid of the effects of the outer iterations.

 for (var i = 0; i < 5; i++) {  (function  (idx) {    setTimeout (function c8> () {      console.log (idx);     5);  }) (i);}
Manufacturing Function Builder

If we are going to implement a series of functions: ADD10,ADD20. we have constructed a constructor named Adder, as follows:

var function (x) {  var base = x;   return function (n) {    return n + base;  };}; var add10 = Adder (ten); Console.log (ADD10 (5)); var = adder (add20), Console.log (ADD20 (5));

Each time adder is called, Adder returns a function to us. The value we pass to adder is stored in a variable named base. Since the returned function references the value of base, the reference count of base is + 1. Base also persists when the return function is not garbage collected.

What are the drawbacks of closures?

Because the closure will make the variables in the function are stored in memory, memory consumption is very large, so can not abuse closures, otherwise it will cause the performance of the Web page, in IE may lead to memory leaks. The workaround is to remove all unused local variables before exiting the function.

Reference:
Learn JavaScript closures (Closure)

Node-lessons/lesson11 at Master Alsotang/node-lessons GitHub

JavaScript scope chain

Understanding function Scopes and closures

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.