为什么我的全局变量在函数中不可访问? [英] Why my global variable is not accessible within a function?

查看:388
本文介绍了为什么我的全局变量在函数中不可访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为 myColor 可以从 sayColor()本地上下文访问,但即便如此我也不会在第一次警报后宣布myColor。为什么?

I thought that myColor would be accessible from sayColor() local context but it isn't even though I'm declaring myColor after the first alert. Why?

var myColor = "blue";
function sayColor() {
    alert(myColor); //undefined expected blue
    var myColor = "green";
    alert(myColor); //green
}
sayColor();


推荐答案

这里发生的事情叫做吊装。使用 var <的变量声明/ code> 和函数语句被提升到其包含范围的顶部。 (请注意,从ES6开始, const 有不同的语义。)所以,对于浏览器来说,你的代码实际上是这样的:

What's going on here is called "hoisting". Variable declarations that use var and function statements are "hoisted" to the top of their containing scope. (Note that, from ES6 on, let and const have different semantics.) So, to the browser's mind, your code actually looks like this:

var myColor = "blue";
function sayColor() {
    var myColor;
    alert(myColor); //undefined expected blue
    myColor = "green";
    alert(myColor); //green
}
sayColor();

来自 MDN


变量的每个定义都是实际上是在其范围顶部的变量声明和定义所在位置的赋值。

Every definition of a variable is really a declaration of the variable at the top of its scope and an assignment at the place where the definition is.

这篇关于为什么我的全局变量在函数中不可访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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