JavaScript Scopes and scope chains

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.