【发布时间】: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