Se la dichiarazione dell'ambito delle forze. Inserendolo in una funzione ci si assicura che le variabili create e chiamate non vengano nuovamente dichiarate o che non si stiano chiamando accidentalmente variabili dichiarate altrove.
così .....
var variable = 5; // this is accessible to everything in the page where:
function()
{
var variable = 7 // this is only available to code inside the function.
}
Ecco un link al sito di Douglas Crockford parlando portata in Javascript:
http://javascript.crockford.com/code.html
di follow-up sul commento qui sotto:
L'ambito JavaScript è un po '"rotto":
function()
{
var x = 3; // accessible in the entire function.
//for scope reasons, it's better to put var y = 8 here.....
if(x != 4)
{
var y = 8; //still accessible in the entire function.
//In other languages this wouldn't be accessible outside
//of the if statement, but in JavaScript it is.
}
}
piuttosto sicuro che questo è un duplicato .... –