This article analyzes the scope chain of JavaScript functions in an example. Share it for your reference. The specific analysis is as follows:
Scope chain:
Each function function in JavaScript has its own scope. It is saved using Active Object (AO for short) active objects, and a scope chain is formed in nested functions, as shown in the figure below:
The scope chain is the AO chain from the inside to the outside
Variable search:
If the variables used in function fn3 cannot be found within the scope of fn3, then search for the outer fn2 scope, and so on until the global object window
The code demonstration is as follows:
var c = 5; function t1(){ var d = 6; function t2(){ var e = 7; var d = 3; //If var d = 3 declared here, then the function will not look for the variable d outward, and the output value is 15 console.log(c+d+e); } t2(); } t1();After understanding the JavaScript scope chain, use external variables with a higher frequency in the function. It is best to save the external variables as local variables before performing operations, which greatly reduces the time to find variables through the scope chain.
I hope this article will be helpful to everyone's JavaScript programming.