为什么在内部范围内未定义x? [英] Why is x undefined in inner scope?

查看:93
本文介绍了为什么在内部范围内未定义x?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中

var x = 1;

(function () {
  console.log(x);
  var x = 2;
}());

为什么当console.log(x),x未定义时?

Why is it that when console.log(x), x is undefined?

推荐答案

可变吊装。实际代码就像这样执行。

Variable hoisting. The actual code is executed like this.

var x = 1;
(function() {
    var x; // x = undefined
    console.log(x);
    x = 2;
})();

编辑:根据Lister先生的建议,有点关于变量提升。来自MDN( https://developer.mozilla.org / en-US / docs / Web / JavaScript / Reference / Statements / var ):

On Mr Lister's advice, a bit on variable hoisting. From MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var):

变量声明,无论它们出现在哪里,都会在任何代码之前处理用var声明的变量的范围是它的当前执行上下文,它是封闭函数,或者对于在任何函数之外声明的变量,是全局的。

"Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global."

这篇关于为什么在内部范围内未定义x?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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