The scope and scope chain of javascript are the most painful part of my learning, because I spent a lot of time reading many technical documents but couldn't understand it. I roughly knew what it meant, but I still couldn't tell why.
Through my extensive testing and reading technical documents, I have summarized the following understanding. Although it is not very technical, I can really understand it.
1. JavaScript is only divided into global and local, and there are no various modifiers for those background languages. If you do not use var in a function, it is global. as follows:
<script type="text/javascript"> varname="c#";//Global window.name="java";//Global varlanguage=function() { alert(name); name="javascript";//Global var name="JS";//Local alert(name); }() alert(name); </script>The above code represents globally all point to the same variable, and the following definition will replace the above. Regarding the three alerts, namely underfind, js, and javascript. This is the scope that plays a role.
2. The scope chain starts from level 0 and is arranged downwards in sequence. The so-called downwards in sequence refer to the arrangement of children. When looking for variables, first look for them from the same level and then look for the parent level.
In the above example,
The first thing that pops up is the first alert in the language method. If the global window is 0, then in the example var name="js" is 1. The first alert is found in 1. If it cannot be found, look for it in 0. This is it found that there is a var name="js" in the same level, but it has not assigned a value yet, so the underfind pops up
The second pop-up is the second alert in the language method, and he will look for it in 1, that is, the inside of the method. He found the name and assigned js, so the pop-up is js
The third pop-up is the alert at the bottom. Since the global name has been reassigned inside the method, JavaScript pops up.
Then add the next link, we top a method in the language, as follows:
<scripttype="text/javascript"> varname="javascript";//global window.name="javascript";//global varlanguage=function() { alert(name); name="javascript";//global varname="JS";//local alert(name); var lovelanguage=function(){alert(name); }(); }() alert(name);</script>At this time, the alert in lovelanguage pops up with js because it will find the name in the language level, which is the name in the language. . .
The above is all the content of the JavaScript scope and scope chain (must-read for novices) brought to you by the editor. I hope everyone will support Footstep Home more.