变量:局部范围,全局范围还是JavaScript引擎? [英] Variable: local scope, global scope or is it the JavaScript engine?

查看:92
本文介绍了变量:局部范围,全局范围还是JavaScript引擎?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在javascript中学习范围时发现的有趣内容。

Here is something interesting I found while learning scope in javascript.

代码

var foo = "This is a global variable.";

var bar = function() {
    alert(foo);
    foo = "Value has been modified";
}

bar();
alert(foo);

这给出了您认为可以得到的正常回复,但如果我改变这一行:

This gives the normal response you think you would get, but if I change this one line:

来自:

foo = "Value has been modified";

to:

var foo = "Value has been modified";

我得到foo的undefined值,为什么会这样?由于该函数是全局范围,它怎么不接受前面的 var 关键字?

I get a value of undefined for foo, why is this? Since the function is global scope how come it doesn't accept the var keyword in front of it?

编辑

现在我基本了解功能栏中 var foo 发生的事情将变得最重要由于var关键字而被提升,但它会被提升而没有分配值

Now I understand basically what is happening the var foo in the function bar will gain most importance because of the var keyword and get hoisted up, but it will be hoisted up without the value it has been assigned.

推荐答案

var 语句中,它有两个部分 - 实际声明:

In a var statement, there are two parts to it - the actual declaration:

var foo //;

...和分配,这是可选的:

... and the assignment, which is optional:

= 1234567890;

如果没有完成任务,变量(如果尚未定义)默认为 undefined

If there is no assignment done to it, the variable (if not already defined) defaults to undefined.

变量声明部分被移动到当前范围的顶部(函数的开头),但是不是实际的赋值(所以它等同于以下):

The variable declaration part is moved to the top of the current scope (the start of the function), but not the actual assignment (so it's equivalent to the following):

var foo = "This is a global variable.";

var bar = function() {
    var foo; // undefined
    alert(foo); // yes, it's undefined
    foo = "Value has been modified"; // modify local, not global
}

bar();
alert(foo); // the global one

函数创建自己的范围 - 例如,取这个:

Functions create their own scope - for example take this:

var test = function ()
{   var bar = 1;
    console.log(bar); // 1
};
test();
console.log(bar); // ReferenceError: bar is not defined

这篇关于变量:局部范围,全局范围还是JavaScript引擎?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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