JavaScript function scope chain analysis _ javascript skills

Source: Internet
Author: User
This article mainly introduces the JavaScript function scope chain. The example analyzes the principle and usage skills of the function scope chain, and has some reference value, if you need it, you can refer to the examples in this article to analyze the JavaScript function scope chain. Share it with you for your reference. The specific analysis is as follows:

Scope chain:

Each function in JavaScript has its own scope. It is saved using Active Object (AO) activity objects and forms a scope chain in nested functions, as shown in:

The scope chain is the AO chain from the inside out

Search for variables:

Variables used in the fn3 function, if not found in the fn3 scope, search for the outer fn2 scope, and so on until the Global Object window

The code is demonstrated as follows:

Var c = 5; function t1 () {var d = 6; function t2 () {var e = 7; var d = 3; // If the declared var d is 3, // The function does not look for the variable d, and the output value is 15 console. log (c + d + e);} t2 ();} t1 ();

After understanding the JavaScript scope chain, you can use frequently-used external variables in the function. It is best to save the external variables as local variables before performing operations, in this way, the time for searching variables through the scope chain is greatly reduced.

I hope this article will help you design javascript programs.

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.