JavaScript closure-block-level scope and private variables

Source: Internet
Author: User
Block-level scope refers to the scope in the code block enclosed by curly braces. There is no block scope in JavaScript. To understand this concept, let's look at the following example:

Block-level scope

Block-level scope refers to the scope in the code block enclosed by curly braces. There is no block scope in JavaScript. To understand this concept, let's look at the following example:

For (var I = 0; I <10; I ++) {...} alert (I); // The result is 10

In the code above, we define variable I in the for loop. In programming languages such as C ++ and Java, after the loop is executed, the I variable in the for Loop will be immediately recycled. However, in JavaScript, variables will always exist after loop or some judgment is used. We can see from the print results that the value after the for loop is over is 10.

When a variable is used in the global environment for loop or judgment, this variable may affect the variables in the function. Therefore, do not use global variables unless otherwise specified, in addition, global variables are at the top of the scope chain, and the access speed is the slowest.

The block scope solution is to use anonymous functions. Let's look at the following code.

(Function () {for (var I = 0; I <10; I ++ ){......}}) (); // If I is printed directly, an error is returned: I does not define alert (I); // I is not definedfunction fn () {alert (I);} fn ();

In the above Code, we put the code block into an anonymous function, and then immediately called this anonymous function. A pair of parentheses after the anonymous function is noticed, indicating that the anonymous function is called. You can see this method in many JavaScript programs. At this point, the variables in the anonymous function will be recycled after use, and these variables cannot be accessed outside the anonymous function.

During team development, global variables with the same name may be defined. Therefore, we need to develop the following habit: Put the code of global variables into an anonymous function, you can call the anonymous function immediately to execute the global variable code, but these variables are controlled in the scope we want to control.

Private variable

When defining an object, we used the this keyword to set the attributes of the object. The attributes set in this way are called public attributes. We can directly access these attributes through objects.

In C ++, Java, and other programming languages, private keywords are used to define the private attributes of an object. private attributes cannot be directly accessed by objects. So how to define private attributes (private variables) in JavaScript? In fact, it is also very simple. We only need to provide a pair of set and get methods for the object. For example, the following code:

Function Person (name) {// There is no way to directly access the name attribute at this time, because this. name // The access name can only be accessed through this. getName and this. setName to access this. setName = function (value) {name = value;} this. getName = function () {return name;} var p = new Person ("Leon"); alert (p. getName ());

We use this. setName () method to set the name attribute for the object, and use this. getName method to obtain the name attribute of the object. In this way, the object's name attribute cannot be directly accessed because it does not have this. name attribute.

The problem with using the above method to create private variables is that each object stores a large number of functions and consumes a lot of memory. To solve this problem, use static private variables. The Code is as follows:

var name = "";var Person= function(value){  name = value;}Person.prototype.setName = function(value){  name = value;}Person.prototype.getName = function(){  return name;} var p1 = new Person("Leon");alert(p1.getName());p1.setName("Ada");alert(p1.getName());

By placing the setName () and getName () methods into the prototype chain of the object, you can solve the problem of copying multiple methods. However, the above Code has some security risks, that is, the block-level scope problem we mentioned earlier. We can also put this code into an anonymous function to solve this problem.

(Function () {// name is recycled after the function is completed. There is no method to receive var name = ""; Person = function (value) outside) {name = value;} Person. prototype. setName = function (value) {name = value;} Person. prototype. getName = function () {return name ;}}) (); var p1 = new Person ("Leon"); alert (p1.getName (); p1.setName ("Ada "); alert (p1.getName ());

Put the definition of the Person class into an anonymous function and immediately execute the anonymous function. This not only ensures that the object cannot be used to directly access the attribute, but also enables each object to share the copy of the same method.

The above is the JavaScript closure-block-level scope and private variable content. For more information, see PHP Chinese website (www.php1.cn )!

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.