I've a javascript file which has in function (local) variables. For example in the code below there are variables: countries, arr, india, usa, uae, australia, canada, kuwait etc. When I launch my website all of these variables are accessible with window.xyz (eg window.countries, window.usa etc...). I'm really confused why this would happen. I would really appreciate if someone can help me understand this.
MyApp.Helpers.LocationEducationHelper = function() {
function getPopularCountriesArray(){
// var me = this;
arr = [];
countries = MyApp.getAllCountries();
india = countries.get("IN");
usa = countries.get("US");
uae = countries.get("AE");
australia = countries.get("AU");
canada = countries.get("CA");
kuwait = countries.get("KW");
nz = countries.get("NZ");
pk = countries.get("PK");
russia = countries.get("RU");
saudiArabia = countries.get("SA");
southAfrica = countries.get("ZA")
gb = countries.get("GB");
arr.push(india, usa, gb, uae, canada, australia, nz, pk, kuwait, russia, saudiArabia, southAfrica);
return arr
};
return {
getPopularCountriesArray : getPopularCountriesArray
};};
add var before each variable. it's treated as global without it
Variable declared locally inside a function, without "var" treated as global variable. If you want to limit the scope use "var".
Global Declaration
var x = 4; //global variable
(function(){
console.log(x); //returns 4
})();
console.log(x); //returns 4
Local declaration
(function(){
var y = 4; //local variable
console.log(y); //returns 4
})();
console.log(y); // Reference error y is not defined
Local without var
(function(){
z = 4; //global variable
console.log(z); //returns 4
})();
console.log(z); // returns 4
You could rewrite it like this.
MyApp.Helpers.LocationEducationHelper = function() { function getPopularCountriesArray(){ // var me = this; var arr = [], countries = MyApp.getAllCountries(), india = countries.get("IN"), usa = countries.get("US"), uae = countries.get("AE"), australia = countries.get("AU"), canada = countries.get("CA"), kuwait = countries.get("KW"), nz = countries.get("NZ"), pk = countries.get("PK"), russia = countries.get("RU"), saudiArabia = countries.get("SA"), southAfrica = countries.get("ZA"), gb = countries.get("GB"); arr.push(india, usa, gb, uae, canada, australia, nz, pk, kuwait, russia, saudiArabia, southAfrica); return arr }; return { getPopularCountriesArray : getPopularCountriesArray };};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.