Scope
Scope refers to the applicable range of variables
Global scope
Variables that are not defined within any function have global scope
Local scope
A variable defined inside a function has a local scope
var bo=-function EB () {alert (bo)}eb ()
Solution: The variable bo is in the global scope and can be accessed by EB ()
Scope chain
Each variable has a scope, and when you try to access a variable, it starts looking up from the current scope until the global scope, and the path to the lookup is the scope chain.
<! DOCTYPE html>
<body>
<script type= "Text/javascript" >
Window.onload=function () {
for (Var i=1;i<4;i++) {
document.getElementsByTagName ("H" +i) [0].onclick=function () {
Alert (i)
}
}
}
</script>
</body>
Solution: This is a For loop take I problem, then analysis, when the page load for a for loop, to h1,h2,h3 a single click event, when clicked H2 tag, execute anonymous function, anonymous function attempt to access the variable I, in the current scope find I not, Up-level scope access, found variable i, variable i because for loop, i=3, so alert (3). That's the role of the scope chain.
JavaScript Scopes and scope chains