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="">
<meta charset="utf-8"/>
div {
width: 100px;
height: 100px;
border: 1px solid black;
var globalVar = "global";
window.onload = function () {
var localVar = "local";
document.getElementById("Div1").onclick = function () {
var insideDiv1Click;
//Do some logic here...
Search WWH ::

Custom Search