Javascript Closures and variables

Source: Internet
Author: User

1. Closures and variables

The mechanism of the scope chain in JavaScript leads to the side effect that closures can only get the last value of any variable in the containing function. A closure holds the entire variable object, not a particular value.

1 2 3 4 5 6 7 8 9 Ten One A - - function createFunctions(){      var result=new Array();              for (var i=0;i<10;i++){          result[i]=function(){              return i;          };          return result;  var funcs = createFunctions();  for (var i=0; i < funcs.length; i++){      document.write(funcs[i]() + "<br />");  }

The Createfunction () function returns an array. On the surface, it seems that each function should return its own index value, but that is not the case, in fact the return value of each function is 10. Because each function's scope chain contains the active objects of the createfunctions () function, they refer to the same variable i. When the Createfunctions () function returns, the value of the variable i is 10, at which point each function refers to the same variable object that holds the variable i, so each function returns 10.

Of course we can use anonymous functions to force the behavior of closures to match expectations.

1 2 3 4 5 6 7 8 9 Ten One A - - the - function createFunctions(){       var result=new Array();                 for (var i=0;i<10;i++){           result[i]=function(num){             return function(){               return num;           };           }(i);     }       return result;   }   var funcs = createFunctions();   for (var i=0; i < funcs.length; i++){       document.write(funcs[i]() + "<br />");   }

After overriding the previous createfunctions () function, each function returns to its different index values. Here, instead of assigning the closure to a value directly, we define an anonymous function and assign the result of executing the function immediately to the array. The anonymous function here has a parameter num, which is the value that the final function will return. When we call each anonymous function, we pass in the variable i. Because the function parameter is passed by value, the current value of the variable i is copied to the parameter num. Inside this anonymous function, there is a closure that creates and returns a access to Num. With this dependency, each function in the result array has its own copy of the NUM variable, so you can return different values.

1.2 About this object

The use of this object in closures has some problems with the This object, which is bound by the run-time function-based execution environment: in a global function, this equals window, and when the function is treated as a method call of an object, this is equal to that object. However, the execution environment of an anonymous function is global, so its this object usually points to window (of course, this points to other objects when the function execution environment is changed by call () and apply ().

1 2 3 4 5 6 7 8 9 Ten One var name="The Window"    var object={      name:"My object"    getNameFunc:function(){          return function(){              return this.name;              };              };  alert(object.getNameFunc()()); //"The Window"(在非严格模式下)

?

The above code creates a global variable name, has created an object containing that property, and this object also includes a method--getnamefunc (), which returns an anonymous function, and the anonymous function returns THIS.NAME. Because Getnamefunc () return a function. So calling Object.getnamefunc () () immediately returns the function that called it, and the result returns a string. However, this example returns the string "the Window", which is the value of the global name variable.

However, why does the anonymous function not get the This object that contains the scope (or external scope)?

Each function is called, and its active object automatically acquires two special variables: this and arguments. The intrinsic function searches for these two variables only to find its active object, so it will never be able to access the two variables in the external function. However, the this object in the outer scope is stored in a variable that the closure can access, and the object can be accessed by a closed packet.

1 2 3 4 5 6 7 8 9 Ten One A var name="The Window"    var object={      name:"My object"    getNameFunc:function(){          var that=this;         return function(){              return that.name;              };              };  alert(object.getNameFunc()()); //"My object"

In the above code, we assign the this object to the that variable before we define the anonymous function, and after the closure is defined, the closure can also access the variable because it is a variable that we deliberately declare in an external function. Even after the function returns, this is still referenced by the object, so calling Object.getname () () returns "My object".

Javascript Closures and variables

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.