JavaScript function scope chain analysis _javascript techniques

Source: Internet
Author: User

This article analyzes the scope chain of JavaScript function. Share to everyone for your reference. The specific analysis is as follows:

Scope Chain:

Each of the function functions of JavaScript has its own scope, which is saved by using active object (called AO) active objects, forming a scope chain in each nested function, as shown in the following illustration:

The scope chain is the AO chain from the inside to the outside.

The search for variables:

Variables that are used in the function fn3, such as if they are not found within the FN3 scope, look for the outer fn2 scope, and so on, until the Global object window

The code demonstrates the following:

var c = 5; 
function T1 () { 
  var d = 6; 
  Function T2 () { 
    var e = 7; 
    var d = 3;
 If the var d = 3 declared here,
 //Then the function is not looking out for the variable d, the output value is 
    console.log (c+d+e); 
  } 
  T2 (); 
} 
T1 ();

After understanding the JavaScript scope chain, use the higher frequency external variables inside the function, it is best to save the external variable as a local variable, then do the operation, thus greatly reducing the time to find the variable through the scope chain.

I hope this article will help you with your JavaScript programming.

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.