全局JavaScript变量范围:为什么这不起作用? [英] Global JavaScript Variable Scope: Why doesn't this work?

查看:87
本文介绍了全局JavaScript变量范围:为什么这不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在玩JavaScript并遇到了我认为奇怪的事情。有人能够解释以下内容吗? (我已将警报值作为注释包含在内)

So I'm playing around with JavaScript and came across what I think to be an oddity. Is anyone able to explain the following? (i've included the alerted values as comments)

为什么foo()内的第一个警报(msg)返回 undefined 而不是在外面

Why is the first alert(msg) inside foo() returning undefined and not outside?

var msg = 'outside';

function foo() {
  alert(msg); // undefined

  var msg = 'inside';
  alert(msg); // inside
}

foo();    
alert(msg); // outside

考虑到这些都可以正常工作:

Considering these both work fine:

var msg = 'outside';

function foo() {
  alert(msg); // outside
}

alert(msg); // outside

和:

var msg = 'outside';

function foo() {
  var msg = 'inside';
  alert(msg); // inside
}

alert(msg); // outside


推荐答案

你的第一个例子中发生的事情是msg的声明和初始化正在拆分,声明被提升到闭包的顶部。

What is happening in your first example is the declaration and initlization of msg are being split with the declaration being hoisted to the top of the closure.

var msg; //declaration
msg = "inside" //initialization

因此您编写的代码是同样的事情

Therefore the code you wrote is the same thing as

var msg = 'outside';

function foo() {
var msg;  
alert(msg); // undefined
msg = 'inside';
alert(msg); // inside
}

第二个例子不一样。在第二个示例中,您尚未声明本地变量msg,因此alert(msg)引用全局消息。
这里有一些进一步的阅读:
吊装

The second example is not the same. In your second example you have not declared a local variable msg so alert(msg) refers to the global msg. Here is some further reading on: Hoisting

这篇关于全局JavaScript变量范围:为什么这不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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