为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

饮歌长啸 2023-01-06 11:01:17
如果我理解正确,在函数内部不使用关键字 var 声明变量将创建一个全局范围的变量。但是当从其容器函数外部访问变量时,我得到这个“ReferenceError: oopsGlobal is not defined”。,,, // 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,,,
查看完整描述

2 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

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


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


// 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


查看完整回答
反对 回复 2023-01-06
?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

发生这种情况是因为您实际上从未跑步过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()调用的) 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)


查看完整回答
反对 回复 2023-01-06
  • 2 回答
  • 0 关注
  • 113 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信