javascript - 函数内部的全局变量不能在外部访问
问题描述
如果我理解正确,在函数内不使用关键字 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()
。如果你不调用一个函数,里面的代码永远不会被执行。
参考错误:
// 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)
推荐阅读
- azure - 已删除 UP 设备中的任务移至新添加的设备
- node.js - Node JS:升级订阅时,Stripe 支付意图为空
- python - 在 MS Access 中使用 to_sql(... , method='multi') 时出错
- c++ - 显式模板实例化示例
- java - 尽管将其中一个 Spring 配置文件添加到环境变量中,但它没有被激活
- bash - 如何在一个循环中同时运行多个任务
- javascript - 重构 A && B && B > A
- python - pytest 需要 10 分钟在 builtins compile 方法收集
- java - 方法重载技术
- java - 如何解决这个反射错误?java.lang.reflect.Field.get(Field.java:393)