The concept of closures in Javascript

Source: Internet
Author: User

Always say closed package, in fact, I do not know what the closure is what the meaning, today, Baidu found a closed packet of relevant information, reference finishing, hope later can be useful;

Closures are actually a difficult part of the JavaScript language and a feature of the language, and many advanced applications are said to be supported by closures.

First understand the following concepts:

1. Scope of variables

In JavaScript, declaring variables using the var keyword, a little understanding of the students know that the VAR keyword declared variable is a local variable, and vice versa is a local variable

For example:

var text = ' Hello '; Local variables

Text = ' World '; Global variables

Where local variables and global variables are most commonly applied, it is self-evident that they are functions;

Local variables:

var x = 1;

function Demo1 () {

alert (x);

}

Demo1 (); Results 1

function Demo1 () {

var x = 1;

}

alert (x); Result error

Global variables:

function Demo1 () {

x = 1;

}

Demo1 ();

alert (x); Results 1

Summary: Declare variables to add Var, responsible, classmate you declare the variable is a global variable!

——————————————————————————————————————————————————

2. How to call or use a local variable externally

The simple method is to define a function inside the function; (insert a few words: personal feeling seems to be somewhat similar to some of the processing methods in the object of PHP, simply say, in a class, using protecte in public)

Direct:

function Demo1 () {

var x = 1;

function Demo2 () {

alert (x); Results 1

}

}

Demo1 ();

The concept of closures in Javascript

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.