开发者

Question related to javascript's var keyword

Does anyone know why the last alert in the code below complains that a is undefined. Shouldn't a is 11 because it's initialized in four() without using the var keyword? Thanks.

function three() {
  var开发者_运维知识库 a = 12
  function four() {
    a = 11
    function five() {
      alert(a)
    }
    return five
  }
  return four
}
three()()()
alert(a)


No, because a has been declared with "var", the assignment to a in four() refers to that declared variable, and the scope of a is limited to three().


var a is in local scope of function three()


The last alert complains about a being undefined because of a scope issue. Since a was declared within a function, the last line(your alert statement) has absolutely no idea about a.


Also, since we're on the topic of scope in JS, I'd like to point out that there is no block-scope in JavaScript, only function and global. Anytime you skip the var, the declaration is effectively global. This catches a lot of people off-guard.


Since variable a is in the local scope of function three you are getting undefined.

This should give the value of a

function three() 
{
    var a = 12;
    function four() {
        a = 11;
        function five() {
            return a;
        }
        return five;
    }
    return four;
}

var b = three()()();
alert(b);


function three() {
    var a = 12
    function four() {
        a = 11
        function five() {
             alert(a)
         }
    return five
    }
return four
}
three()()()
alert(a)     

Simply put, a isn't defined because well, it isn't defined.

You don't have a variable a outside of your functions. To grossly simplify it, things inside a set of curlies don't exist outside that set of curlies.

You could define it before the function or pass it into the function to fix this

function three() {
    a = 12
    function four() {
        a = 11
        function five() {
             alert(a)
         }
    return five
    }
return four
}
three()()()
alert(a)     

Edit for comment: Variables declared without var are always global, so getting rid of the var in 3 would do that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜