13th: Creating a local scope with an immediately called function expression

Source: Internet
Author: User

13th: Creating a local scope with an immediately called function expression
What does this program (BUG program) output?

function Wrapelements (a) {var result = [], I, N;  for (i = 0, n = a.length; i < n; i++functionreturn  a[i];}; return result;} var wrapped = wrapelements ([ten, +, +, +]); var f = wrapped[0//  ?

The

Programmer might want this program to output 10, but it actually outputs the undefined value.
the way to figure out this example is to understand the difference between binding and assignment. At run time into a scope, JavaScript
allocates a slot (slot) in memory for each variable bound to that scope. The wrapelements function binds
Three local variables: result, I, and N. Therefore, when it is called, the wrapelements function will divide the three variables
with slots. In each iteration of the loop, the loop body assigns a closure to the nested function. The Bug in the program is
The fact that the programmer seems to expect that the function stores the value of the variable i when the nested function was created. But in fact, it
stores a reference to the variable i. Because the value of the variable i is changed every time the function is created, the inner function eventually
sees the last value of the variable i. It is worth noting that closures store references to external variables instead of values.
Therefore, all closures created by the Wrapelements function refer to the same total
of the variable I created before the loop. Since each iteration of the loop increments the variable i until it runs to the end of the array, this is actually when we tune
with either of these closures, it looks for the array's index 5 and returns the undefined value.
Note that even if we place the Var declaration on the head of the For loop, the Wrapelements function behaves exactly
as well.

 function   Wrapelements (a) { var  result = [];  for  (var  i = 0, n = a.length; i < n; i++= function  () { A[i]; };} return   result;}  var  wrapped = wrapelements ([Ten, A, a, a 50var  f = Wrapped[0];f ();  //  undefined  

This version looks more deceptive because the Var declaration appears in the loop body. But as always, variable declarations
will be lifted to the top of the loop. Once again, the variable i is only assigned a "slot".
The workaround is to force the creation of a local scope by creating a nested function and calling it immediately.

function Wrapelements (a) {var result = [];  for (var i = 0, n = a.length; i < n; i++) {(function() {var j =
   
    function
    return 
     a[j];}) ();} 
    return 
    result;}
   

This technique is called a function expression called immediately, or iife (pronounced "iffy"). It is an indispensable
Resolution of JavaScript lacks a block-level scope method. Another variant is to bind local variables as formal parameters to the Iife
and passes its value as an argument.

function Wrapelements (a) {var result = [];  for (var i = 0, n = a.length; i < n; i++) {(functionfunctionreturn a[j];};}) (i);} return result;}

However, use Iife to create a local scope with caution, because wrapping a block of code in a function can lead to code
The block has undergone some subtle changes. First, the code block cannot contain any break statements and continue statements that jump out of a block.
Because it is illegal to use break or continue outside of a function. Second, if the code block references this or a special
Arguments variables, Iife will change their meaning. The 3rd chapter will discuss working with this and arguments variables
of technology.


Tips
Understand the difference between binding and assignment.
Closures capture their external variables by reference instead of by value.
Use a function expression called immediately (Iife) to create a local scope.
Beware of situations in which the wrapped code block may change its behavior in an immediately invoked function expression.

Source: Effective JavaScript books

13th: Creating a local scope with an immediately called function expression

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.