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.