JS:为什么"x"变量的值未定义?

dar*_*ong 1 javascript function hoisting

为什么x下面示例中的变量返回undefined而不是25?

var x = 25;

(function() {
  console.log(x);
  var x = 10;
})();
Run Code Online (Sandbox Code Playgroud)

brk*_*brk 5

这是在javascript 中提升的常见问题.代码实际上看起来像这样.值在之后分配console.log.

第二个未定义(如果在开发人员的工具上运行)是因为该函数没有显式返回任何内容

这就是Javascript实际执行代码的原因var:

var x = 25;

(function() {
  var x;
  console.log(x);
  x = 10;
})();
Run Code Online (Sandbox Code Playgroud)