3. Variable
scope
• Global
and
local
variables
• JS
does
not
have
block
statement
scope!
function test() {
if(true) {
var x = 5;
}
document.write(x);
}
• This
works!
X
is
defined
in
the
scope
of
the
func1on
(or
globally)
4. Hois1ng
• Variables
are
moved
on
top
of
the
func1on!
function test() {
var x;
if(true) {
x = 5;
}
document.write(x);
}
6. Hois1ng
function test() {
var x;
document.write(x); // Prints undefined!
if(true) {
x = 5;
}
}
7. So
what
happens
here?
var x = 10;
function test() {
document.write(x);
if(true) {
var x = 5;
}
}
8. So
what
happens
here?
var x = 10;
function test() {
var x; // Overrides the global one..
document.write(x); // undefined
if(true) {
x = 5;
}
}
9. Global
Objects
• Global
variables
are
in
fact
proper1es
of
the
global
object!
•
In
web
pages
the
global
object
is
window
• So
– var
x
=
5
ó
window.x
=
5;
10. Objects
var Sales = "Toyota";
function CarTypes(name) {
if (name == "Honda")
return name;
else
return "Sorry, we don't sell " + name + ".";
}
var car = { myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales };
document.write(car.myCar); // Saturn
document.write(car.getCar); // Honda
document.write(car.special); // Toyota