为什么这在 javascript 中有效? [英] Why does this work in javascript?

查看:48
本文介绍了为什么这在 javascript 中有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚才,我看到了一些这样的代码:

Just now,I saw some code like this:

if(condition){
    var xx='sss';   
}
//do something

if(condition){
    console.info(xx);
}

<小时>

现在,我只是想知道为什么第二个 if 语句有效?xx 变量是另一个if 语句中定义的局部变量,如何访问它?


Now, I just wonder why the second if statement work? How can it access the xx variable since it is a local variable defined in another if statement?

推荐答案

var 在 JavaScript 中的作用域限定为包含执行上下文(例如,整个函数的作用域,或者整个全局作用域,如果 var 在全局范围内),不是块.JavaScript(还)没有块作用域(ECMAScript6 看起来可能会通过新的 let 关键字添加它).

var in JavaScript is scoped to the containing execution context (e.g., the whole function's scope, or the whole global scope if the var is at global scope), not the block. JavaScript doesn't (yet) have block scope (ECMAScript6 looks likely to add it, via the new let keyword).

您引用的代码完全等价于:

var xx;   
if(condition){
    xx='sss';   
}
//do something

if(condition){
    console.info(xx);
}

规范的第 10.5 节涵盖了这一点,它描述了引擎在进入一个新的执行上下文.(它基本上是一个两阶段的过程,首先设置所有声明,然后逐步执行代码.)

This is covered by Section 10.5 of the specification, which describes what the engine does when entering a new execution context. (It's basically a two-phase process, first setting up all the declarations, and then executing step-by-step code.)

更多:可怜的被误解的var

这篇关于为什么这在 javascript 中有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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