【问题标题】:Global variable inside a function cant be access outside函数内部的全局变量不能在外部访问
【发布时间】:2020-08-13 00:55:22
【问题描述】:

如果我理解正确,在函数内不使用关键字 var 声明变量将创建一个全局作用域变量。

但是从容器函数外部访问变量时,我得到了这个“ReferenceError: oopsGlobal is not defined”。

,,,
 // Declare the myGlobal variable below this line
var myGlobal = 10 

function fun1() {
  // Assign 5 to oopsGlobal Here
  oopsGlobal = 5
}

// Only change code above this line

function fun2() {
  var output = "";
  if (typeof myGlobal != "undefined") {
    output += "myGlobal: " + myGlobal;
  }
  if (typeof oopsGlobal != "undefined") {
    output += " oopsGlobal: " + oopsGlobal;
  }
  console.log(output);
}

console.log(oopsGlobal) // ReferenceError: oopsGlobal is not defined
,,,

【问题讨论】:

  • 您没有调用/执行您的fun1(),因此...您可以正确猜测会发生什么。这就像 oopsGlobal 从未定义或分配给任何 Global 对象。在您的 console.log 之前致电 fun1();
  • 没有var 的赋值不是声明。这只是一个赋值,在赋值实际执行之前不会创建全局属性。

标签: javascript


【解决方案1】:

这是因为您从未真正运行过fun1()。如果你不调用一个函数,里面的代码永远不会被执行。

参考错误:

 // Declare the myGlobal variable below this line
var myGlobal = 10 

function fun1() {
  // Assign 5 to oopsGlobal Here
  oopsGlobal = 5
}

// Only change code above this line

function fun2() {
  var output = "";
  if (typeof myGlobal != "undefined") {
    output += "myGlobal: " + myGlobal;
  }
  if (typeof oopsGlobal != "undefined") {
    output += " oopsGlobal: " + oopsGlobal;
  }
  console.log(output);
}

console.log(oopsGlobal) // ReferenceError: oopsGlobal is not defined


没有 ReferenceError(注意 fun1() 被称为 before console.log()

 // Declare the myGlobal variable below this line
var myGlobal = 10 

function fun1() {
  // Assign 5 to oopsGlobal Here
  oopsGlobal = 5
}

// Only change code above this line

function fun2() {
  var output = "";
  if (typeof myGlobal != "undefined") {
    output += "myGlobal: " + myGlobal;
  }
  if (typeof oopsGlobal != "undefined") {
    output += " oopsGlobal: " + oopsGlobal;
  }
  console.log(output);
}

fun1()
console.log(oopsGlobal)

【讨论】:

    【解决方案2】:

    您已经编写了代码,但从未调用过它。 fun1fun2 永远不会运行。我在下面添加了一行调用 fun1() 导致分配发生的函数。

    这更像是一个提供演示的答案——您很可能不想实际编写具有全局变量或类似副作用的代码。如果您正在为浏览器编写软件,使用windowglobalThis 来存储您的全局状态也可能会更清晰。

    // Declare the myGlobal variable below this line
    var myGlobal = 10 
    
    function fun1() {
      // Assign 5 to oopsGlobal Here
      oopsGlobal = 5
    }
    
    fun1(); // You wrote the functions previous, but you never CALLED them.
    
    // Only change code above this line
    
    function fun2() {
      var output = "";
      if (typeof myGlobal != "undefined") {
        output += "myGlobal: " + myGlobal;
      }
      if (typeof oopsGlobal != "undefined") {
        output += " oopsGlobal: " + oopsGlobal;
      }
      console.log(output);
    }
    
    console.log(oopsGlobal) // ReferenceError: oopsGlobal is not defined

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-08
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 2011-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多