HTML and CSS Reference
In-Depth Information
This objective covers how to:
Establish the lifetime of variables and variable scope
Avoid using the global namespace
Leverage the this keyword
Establishing the lifetime of variables and variable scope
Variables begin their life with a declaration. The remainder of their life within the application
depends on where the variables are declared.
To declare a variable in JavaScript, you use the var keyword.
var myVariable;
You can declare many variables concurrently. For example, the following code declares
three variables:
var x, y, z;
You can also initialize your variables inline with the declaration, giving them immediate
nondefault values:
var x =0.0, y=0.0, z=0.0
Until a variable is initialized, it's not really “alive”—it has a value of undefined. After a vari-
able is available for use, it's considered to be “in scope.” The duration over which the variable
remains in scope depends on where the variable is declared. A variable that has global scope
is available throughout the webpage. A variable with local scope is available only within a
specified context, as Listing 1-7 shows.
LISTING 1-7 An example to demonstrate variable scope
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8"/>
<style>
div {
width: 100px;
height: 100px;
border: 1px solid black;
}
</style>
<script>
var globalVar = "global";
window.onload = function () {
var localVar = "local";
document.getElementById("Div1").onclick = function () {
var insideDiv1Click;
//Do some logic here...
 
 
Search WWH ::




Custom Search