JavaScript变量范围返回“未定义” [英] JavaScript variable scope return "undefined"

查看:85
本文介绍了JavaScript变量范围返回“未定义”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript指南中有一个关于变量范围的句子:JavaScript中的变量在某种意义上被提升或被提升到函数或语句的顶部。但是,未初始化的变量将返回值未定义。

There is one sentence in JavaScript Guide about variable scope:"Variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that aren't initialized yet will return a value of undefined."

   /**
    * Example 2
    */
   // will return a value of undefined
   var myvar = "my value";

(function() {
  console.log(myvar); // undefined
  var myvar = "local value";
})();

我的问题是:为什么console.log(myvar);将返回undefined?我认为第一行已初始化 myvar 一个值为我的价值。

My question is: Why the "console.log(myvar); "will return undefined? I think the first line has initialized myvar a value which is "my value".

推荐答案

因为所有变量声明都自动提升到其定义功能块的顶部,此代码:

Because all variable declarations are automatically hoisted to the top of their defining function block, this code:

(function() {
  console.log(myvar); // undefined
  var myvar = "local value";
})();

实际上是JS解释器:

(function() {
  var myvar;   // declares a new local variable that covers up the global name
  console.log(myvar); // undefined
  myvar = "local value";
})();

哪个应该显示为什么本地定义 myvar 是什么 console.log()输出并且已经定义,但尚未初始化,因此显示为 undefined

Which should show you why the locally defined myvar is what console.log() outputs and it has been defined, but not yet initialized so thus it shows as undefined.

本地定义的 myvar 会覆盖/覆盖全局定义的 myvar 在你的函数中,你只得到本地定义的变量(无论它是否已经初始化)。

The locally defined myvar overrides/covers up the globally defined one so when you access myvar in your function, you only get the locally defined variable (whether it's been initialized yet or not).

查看其他一些参考资料相同主题:

See some other references on the same topic:

JavaScript变量如何工作?

JavaScript变量未定义与未定义

JavaScript中每个函数一个var?

JavaScript'悬挂'

如果删除 var 在你的函数中(所以你只是引用一个变量,而不是声明一个新变量),那么你只有一个名为 myvar 的全局变量,你会得到它看起来像你可能期望的行为:

If you remove the var in your function (so you are just referencing a variable, not declaring a new one), then you would only have one global variable named myvar and you would get the behavior it looks like you may be expecting:

var myvar = "my value";

(function() {
  console.log(myvar); // outputs "my value"
  myvar = "local value";
})();

这篇关于JavaScript变量范围返回“未定义”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆