Differences between javascript nested functions and external functions called in Functions

Source: Internet
Author: User

Differences between javascript nested functions and external functions called in Functions

We all know that the local variables defined in a function are always defined within the declared function Body and Its nested functions, in addition, an object always points to a global object in the function scope chain, so that the function can access global variables.

Var ga = 'global'; var func = function () {var la = 'local'; return function () {return function () {alert (la); alert (ga) ;}}} a = func (); a (); // The local and global

So when function A is called by function B in the body of the function, can A access the local variables defined in function B? The answer is no. Modify the above example as follows:

Var ga = 'global'; function repeat () {alert (la);} var func = function () {var la = 'local'; alert (1 ); repeat (); alert (2) ;}; func ();

The above running result only pops up 1. When calling repeat, the program is interrupted because the undefined variable js interpreter is accessed.

The reason is that the function saves a scope chain during definition. The repeat function is defined externally and there is no local variable named la in its scope, if you continue to search for la in the global scope, an error is reported.

Therefore, nested functions and nested calls to external functions are quite different.

Answer a question yesterday. I hope this article will help friends who are equally confused.

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.