- Global variables can be used anywhere inside of a program.
- Local (function) variables are variables that you create inside of a protected program within a program, called a function.
var movie = "The Godfather";
function showGoodMovie () {
alert (movie + " is a good movie!");
}
function showBadMovie () {
movie = "Speed 2: Cruise Control";
alert (movie + " is a bad movie!");
}
Notice that the var keyword is missing from before the movie variable in showBadMovie(). JavaScript assumes that you want to override the global movie variable, rather than create a local function variable. The results are positively disastrous!
showGoodMovie(); // pops up "The Godfather is a good movie!"
showBadMovie(); // pops up "Speed 2: Cruise Control is a bad movie!"
/* Oh no! The global variable is now Speed 2: Cruise Control, not the good movie name anymore! */
showGoodMovie(); // pops up "Speed 2: Cruise Control is a good movie!"
No comments:
Post a Comment