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