函数内部的全局变量不能在外部访问

如果我理解正确,在函数内部不使用关键字 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

,,,


饮歌长啸
浏览 124回答 2
2回答

慕码人8056858

您编写了代码,但从未调用过它。fun1并且fun2永远不会运行。我在下面添加了一行,它调用了fun1()导致分配发生的函数。这更像是提供演示的答案——您很可能不想实际编写具有全局变量或像这样的副作用的代码。如果您正在为浏览器编写软件,使用window或globalThis存储您的全局状态也可能使它更清晰。// Declare the myGlobal variable below this linevar 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 linefunction 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()。如果你不调用一个函数,里面的代码将永远不会被执行。参考错误: // Declare the myGlobal variable below this linevar myGlobal = 10 function fun1() {  // Assign 5 to oopsGlobal Here  oopsGlobal = 5}// Only change code above this linefunction 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()调用的) console.log() // Declare the myGlobal variable below this linevar myGlobal = 10 function fun1() {  // Assign 5 to oopsGlobal Here  oopsGlobal = 5}// Only change code above this linefunction fun2() {  var output = "";  if (typeof myGlobal != "undefined") {    output += "myGlobal: " + myGlobal;  }  if (typeof oopsGlobal != "undefined") {    output += " oopsGlobal: " + oopsGlobal;  }  console.log(output);}fun1()console.log(oopsGlobal)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript