首页 > 解决方案 > 函数内部的全局变量不能在外部访问

问题描述

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

标签: javascript

解决方案


发生这种情况是因为您从未真正在跑步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)


推荐阅读