【问题标题】:Are Javascript variables not declared (no var) inside functions treated as global?Javascript 变量是否在被视为全局的函数内未声明(无 var)?
【发布时间】: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


【解决方案1】:

函数已声明,但从未调用,这就是它给出错误的原因。 试试这个

function foo() {
    notDeclaredInsideFunction = "Not declared inside function so treated as local scope";
    alert(notDeclaredInsideFunction);
}
foo();

alert(notDeclaredInsideFunction);

【讨论】:

  • 我希望这是因为变量是在调用函数时动态声明的,否则变量未定义。我做对了吗?
  • 是的,就是这个原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-17
  • 1970-01-01
  • 1970-01-01
  • 2012-10-31
  • 2014-01-17
  • 1970-01-01
  • 2011-10-11
相关资源
最近更新 更多