JS is a function-level language, and the scope of a variable is:
Internal can be accessed internally, internal can be accessed externally, external cannot be accessed internally.
If you want to access variables inside the function externally, you need to use closures. A closure means accessing a variable that should not be accessed.
Closure Action 1: Implement encapsulation
Let's take a look at an example of encapsulation, where the variables inside the person cannot be accessed, but are accessed in the form of a closure:
1 varperson =function(){ 2 //variable scope is inside function, external unreachable3 varName = "Default"; 4 5 return { 6GetName:function(){ 7 returnname; 8 }, 9SetName:function(newName) {TenName =NewName; One } A } - }(); - thePrint (person.name);//direct access with a result of undefined - print (Person.getname ()); -Person.setname ("Abruzzi"); - print (Person.getname ()); + - The results were as follows: + A undefined at default -Abruzzi
Closure Action 2: Another important use is to implement object-oriented objects, the traditional object language provides a template mechanism for the class,
Such different objects (instances of classes) have independent members and states, and do not interfere with each other. Although there is no such mechanism in JavaScript, by using closures,
We can simulate such a mechanism. Or in the above example:
1 functionPerson () {2 varName = "Default"; 3 4 return { 5GetName:function(){ 6 returnname; 7 }, 8SetName:function(newName) {9Name =NewName; Ten } One } A }; - - the varJohn =Person (); - print (John.getname ()); -John.setname ("John"); - print (John.getname ()); + - varJack =Person (); + print (Jack.getname ()); AJack.setname ("Jack"); at print (Jack.getname ()); - - The results of the operation are as follows: - - default - John in default -Jack
This code shows that both John and Jack can be referred to as instances of the person class, because these two instances have independent, non-impact access to the name member.
javascript--understanding closure and its effect in early stage