[英]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.