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

Why is javascript treating in function (local) variables as global (window) variables?

本文关键字:变量 全局 窗口 javascript 为什么 局部 函数      更新时间:2023-09-26

我有一个javascript文件,其中包含函数内(本地)变量。例如,在下面的代码中有一些变量:countries、arr、india、usa、uae、australia、canada、kuwait等。当我启动我的网站时,所有这些变量都可以通过window.xyz访问(例如window.countries、window.usa等)。我真的很困惑为什么会发生这种情况。如果有人能帮我理解这一点,我将不胜感激。

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

本地无var

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