【发布时间】:2014-04-26 05:11:42
【问题描述】:
我已经阅读了许多文章甚至 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 未定义。
可能是我遗漏了一些非常简单的东西。
【问题讨论】:
-
函数内部的代码只有在你调用它时才会执行。我很确定函数内的
alert也不起作用,因为您没有调用该函数。
标签: javascript variables scope