为什么javascript将函数(局部)变量视为全局(窗口)变量?

时间:2015-11-06 21:15:02

标签: javascript jquery

我的javascript文件包含函数(本地)变量。例如,在下面的代码中有变量:countries,arr,india,usa,uae,australia,canada,kuwait等。当我启动我的网站时,所有这些变量都可以通过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
};};

3 个答案:

答案 0 :(得分:3)

添加var 在每个变量之前。 它没有它被视为全球

答案 1 :(得分:1)

变量在函数内部声明,没有" 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

没有var的本地

(function(){
    z = 4; //global variable
    console.log(z); //returns 4
})();
console.log(z); // returns 4

答案 2 :(得分:0)

你可以像这样重写它。



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
};};




相关问题