JS Closure Example

Source: Internet
Author: User

vardb =(function () {//Create a hidden object, this object holds some data//This object cannot be accessed from outside.vardata = {};//Create a function that provides some way to access datareturnfunction (key, Val) {if(val = = = undefined) {returnData[key]}//Get    Else{returnData[key] = val}//Set    }//We can call this anonymous method//return this intrinsic function, which is a closed packet}) ();d B ('x');//Back to undefineddb'x',1);//set data[' x '] to 1db'x');//returns 1//We can't access data, the object itself .//but we can set up a member of it

1. When a function is nested within a function, the internal function can access the variables in the external function.

2. External variables (environment variables?) ),

Including:

2.1 Global variables, including DOM.

2.2 Variables or functions for external functions.

If a function accesses its external variables, it is a closed packet.

Technically, in JS, each function is a closure, because it always has access to the data defined outside it.

Closed Package without return:

function Closureexample () {            var;            SetTimeout (function () {                Console.log (+ +temp)            ;  + );        }        Closureexample ()

Closure instances:

  Function Demo () {            var5;            function Add () {                Console.log (temp+ +)            ;            } return add;        }         var demeinstance = demo ();         // the console demeinstance,temp has been added

JS Closure Example

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.