javascript Scope Scope Chain of Newbies must see
- 2021-06-28 11:00:16
- OfStack
The scope and scope chain of javascript are the most painful part of my learning, because I spent a lot of time reading a lot of technical documents and didn't understand them. I knew what it meant, and then I couldn't tell why.
Through my extensive testing and technical documentation, I summarize the following understanding, which is not very technical, but it does.
1. javascript is only global and local, and there are no modifiers for those background languages.Not using var in a function is global.The following:
<script type="text/javascript">
varname="c#";// Overall situation
window.name="java";// Overall situation
varlanguage=function()
{
alert(name);
name="javascript";// Overall situation
var name="JS";// local
alert(name);
}()
alert(name);
</script>
The global ones represented in the code above all point to the same variable, and the following definitions replace the ones above.For the three alerts, underfind, js, and javascript. This is where scopes play a role.
2. Scope chains are ordered down from level 0. The so-called ordering down refers to the ordering of children.When looking for a variable, look for the parent from the same level.
In the example above,
The first alert in the language method pops up first. If window is global 0, var name="js" in the example is 1. The first alert is found in 1, if it is not found in 0.This is when it finds an var name="js" at the same level but it has not been assigned yet, so it pops up underfind
The second pop-up is the second alert in the language method, which in the same way will look inside the method in 1 mile.He found name and assigned js, so js pops up
The third pop-up is the bottom alert, which is javascript because the global name has been reassigned within the method.
Then add the next link We have the top 1 method in language, as follows:
<scripttype="text/javascript">
varname="javascript";// Overall situation
window.name="javascript";// Overall situation
varlanguage=function()
{
alert(name);
name="javascript";// Overall situation
varname="JS";// local
alert(name);
var lovelanguage=function(){
alert(name);
}();
}()
alert(name);
</script>
alert in lovelanguage pops up js at this time because he will go to level 1, name in language, so...
That's all the javascript scope and scope chain (newbies must see) brought to you by this site. I hope you can support your footsteps home more.