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

查看:22
本文介绍了全局 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() 中的第一个 alert(msg) 返回 undefined 而不是 outside?

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) 指的是全局 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天全站免登陆