我读过很多文章甚至是 SO 问题,指出未在函数内声明的 javascript 变量被视为全局变量。 函数内部的“no var”将查找范围链,直到它找到变量或命中全局范围(此时它将创建它):
这是一个 SO 链接。
What is the purpose of the var keyword and when to use it (or omit it)?
但是当我想去执行它的时候,它马上就报错了。
function foo() {
// Variable not declared so should belong to global scope
notDeclaredInsideFunction = "Not declared inside function so treated as local scope";
// Working fine here
alert(notDeclaredInsideFunction);
}
// Giving error : notDeclaredInsideFunction is undefined
alert(notDeclaredInsideFunction);
所以 notDeclaredInsideFunction
应该在全局范围内处理。但是为什么我收到错误,指出未定义 notDeclaredInsideFunction
。
可能是我遗漏了一些非常简单的东西。
最佳答案
函数已声明,但从未被调用,这就是它给出错误的原因。 试试这个
function foo() {
notDeclaredInsideFunction = "Not declared inside function so treated as local scope";
alert(notDeclaredInsideFunction);
}
foo();
alert(notDeclaredInsideFunction);
关于javascript - 函数内部的 Javascript 变量是否未声明(无 var)被视为全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22514646/