Closures and variable scopes

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.

Basic Foundation Foundation Foundation BASE!!! , this is a repeated trampling of the pit, more than once ...

Let's take a first example:


Example 1

Very simple, after execution, print 1, 2, 3, 4, 5. Add anonymous function again


Example 2

Print the n value in the anonymous function, and then print 1, 2, 3, 4, 5. My use of the scene is very simple, advertising has a lot of filter plug-ins, many can be reused the same struct, just according to name to distinguish. Filter conditions to be registered in a global map for subsequent use, as in logic Example 3:


Example 3

The code logic is clear, after the execution of the discovery output is 5, 5, 5, 5, 5 ...

In fact, the principle is very simple, and Python is also very similar, the closure is lazy to generate FN when n is in the For loop outer layer, and so on the execution of FN when n has become 5. It is easy to fix, N to generate a temporary object copy n value in the form of a parameter to FN, or for a for loop.


Example 4

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.