警报未按预期显示。

时间:2014-05-27 04:58:02

标签: javascript jquery

我只是尝试使用以下代码检查范围变化,但结果不是以预期的方式。任何人都可以解释这背后究竟发生了什么......?

var a = 10;

+ function () {
  a = 5;
  var a;
  alert("inline  " + a); //Expected undefined but it displayed as 5
}();

alert(a); //Expected 5 but it alerted 10

DEMO

4 个答案:

答案 0 :(得分:2)

var hoisting

  

因为变量声明(和一般的声明)是   在执行任何代码之前处理,在任何地方声明变量   在代码中相当于在顶部声明它。这也意味着   变量在声明

之前似乎可以使用

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var

编译器将您的代码理解为

var a;
a = 5;

答案 1 :(得分:2)

函数中var声明的位置并不重要。这些完全相同:

function () {
    var a;
    a = 5;
}

function () {
    a = 5;
    var a;
}

答案 2 :(得分:0)

使用" var a"你要求变量的全局值,使用" window.a"显示它:

<script>
var a = 10;

+ function () {
    a = 5;
    var a;
    alert("inline  " + window.a); //Expected undefined but it displayed as 5
}();

</script>

答案 3 :(得分:-1)

var a = 10; // Global scope

+ function () {
    a = 5; // You are not using Var here .. so it is also a global scope
    var a; // Now you are mentioning your a is Var so scope is changed from global to this function
    alert("inline  " + a); // Printing 5 because you local scope a has value of 5.
}();

alert(a); // Printing 10 because of global scope a has value 10