提升全局变量的javascript [英] javascript hoisting for global variable

查看:64
本文介绍了提升全局变量的javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道javascript提升如何用于全局变量.

I was wondering how javascript hoisting works for global variable.

假设我有以下代码段:

var a = 5;
function print(){
    console.warn("a",a,b);
    var a = 10;
    b=5;
    console.warn("a",a);
}
print();

在这种情况下,我收到错误"b未定义".我想知道为什么Java语言提升不适用于全局变量.我试图寻找该结果,但仅获得可变吊装的结果.有什么想法吗?

In this case I am getting error "b is not defined". I wonder why Javascript hoisting is not working for global variable. I tried to look for this but getting results only for variable hoisting. Any thoughts??

推荐答案

var 语句被提升.函数声明被挂起.不会挂起分配(在某种程度上,如果将 var 语句与分配( var foo = 1 )组合在一起,则声明部分将被挂起,但分配不会被挂起)

var statements are hoisted. function declarations are hoisted. Assignments are not hoisted (to the extent that if you combine a var statement with an assignment (var foo = 1) then the declaration part is hoisted but the assignment is not).

这篇关于提升全局变量的javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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