Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

scope - Understanding JavaScript function scoping

The code below is JavaScript code. I am trying to understand function scope in JavaScript and following the article over here. I am reproducing the code below -

var cow = "purple"; // just a random cow

var f = function (x) {
    var r = 0;
    cow = "glue";
    if (x > 3) {
        var cow = 1; // a local variable
        r = 7;
    }
    return r;
};

var z = f(2);
alert(cow); // returns purple

I don't quite understand why the string "purple" is alerted. The line cow = "glue"; should set the value of the cow variable to "glue". If I remove the if block, and then alert cow in the last statement, I see that the string "glue" is alerted.

When f(2) is called, the if code block is not entered and nothing in it gets executed, so why do I see different results ? i.e why does alerting cow in the last statement return the string "purple" now ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Variable declarations inside functions are always hoisted to the top. So your code is actually:

var f = function (x) {
    var cow, r;
    r = 0;
    cow = "glue";
    if (x > 3) {
        cow = 1; // a local variable
        r = 7;
    }
    return r;
};

Inside the function you're always assigning to the local cow, never the global.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...