Java Script What is a closure?

Source: Internet
Author: User
Tags closure

Suppose you now have a function f (x) = a + X

This function is not complete, such as f (1) = a + 1

You have one question: How much is a?

There are two ways to answer this question

The first is called "Dynamic Scope", and the value of a is determined by the value of a in the context of a function call , such as

A = 1;
V=f (1); here V is 2

The problem with dynamic scopes is that each time a function invokes the same parameter, it may not return the same value, and the return value depends on some value of the context

The second type is the lexical scope, and the value of a depends on the value in the context of the function definition .

G (a) = lambda (x) a + x;
f = g (2)

Here the function g returns a function like the above function f, where A is 2, then executes

A = 1;
V=f (1); here V is 3

Because F wants to "remember" the value of a when it is defined by itself is 2, so when implemented

f (x) = a + x and a = 2 are packaged in a block, called "closures", meaning that it is completely independent, relying only on invocation-time parameter evaluation, no longer dependent on the context of the call



Baozii
Links: https://www.zhihu.com/question/21865351/answer/20823147
Source: Know
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.

Java Script What is a closure?

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.