[英]Why is javascript treating in function (local) variables as global (window) variables?
我有一个具有功能(本地)变量的javascript文件。 例如,在下面的代码中有变量:国家,地区,印度,美国,阿联酋,澳大利亚,加拿大,科威特等。当我启动网站时,所有这些变量都可以通过window.xyz(例如window.countries,window)访问。美国等)。 我真的很困惑为什么会发生这种情况。 如果有人可以帮助我理解这一点,我将不胜感激。
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
};};
在每个变量之前添加var。 没有它就被视为全球性的
在函数内部局部声明的变量,不将“ var”视为全局变量。 如果要限制范围,请使用“ var”。
全球宣言
var x = 4; //global variable
(function(){
console.log(x); //returns 4
})();
console.log(x); //returns 4
当地申报
(function(){
var y = 4; //local variable
console.log(y); //returns 4
})();
console.log(y); // Reference error y is not defined
本地无变量
(function(){
z = 4; //global variable
console.log(z); //returns 4
})();
console.log(z); // returns 4
您可以这样重写它。
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 };};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.