About JavaScript closures

Source: Internet
Author: User

To figure out a closure, you must first understand the scope of the variable: global (variable), local (variable). Global variables that can be read directly wherever you are:

var n = 123function  me () {          alert (n);} me (); // must pop 123

Instead of defining a variable inside the function, the outside of the function is naturally not available:

function Me () {     var n = 123;} alert (n); // Error

Of course, learned JS know that if you declare a variable inside a function without Var, it is equivalent to declaring a global variable externally:

function Me () {   = 123;} Me (); alert (n); //   can pop up 123 because the variable n is actually a global variable

So is there any way we can read the internal variables externally? That's the closure, which is a special function: first define a function inside the function body:

function Me () {    var n = 123;         function You () {         ///123  Because me is the parent function of you, naturally you can get your father's property;}   }

Such nesting, embodies the JS language chain scope of the characteristics, that is, the parent function (parent object) All variables are visible to the child function, but the reverse is not possible, like a disobedience, and then external to the internal variables, only need to return the child function

function Me () {    var n = 123;         function You () {         ///123  Because me is the parent function of you, naturally you can get your father's property;   }      return you ;} var our =//  123

This, the disobedience of the conspiracy to succeed!

About the application of closures, I will gradually update to the blog!!

About JavaScript closures

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.