Understanding Javascript Function Scoping
Solution 1:
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 localcow, never the global.
Solution 2:
The two things to understand here are that Javascript variables are hoisted to the top of their scope, and javascript does not have block scope.
So
- All variables in a scope are considered declared at the beginning of the scope
- an if statement does not create a new scope.
So your example is equivalent to
var cow = "purple"; // just a random cowvar f = function (x) {
var cow, r = 0;
cow = "glue";
if (x > 3) {
cow = 1; // a local variable
r = 7;
}
return r;
};
var z = f(2);
alert(cow); // returns purpleThe var declaration in the if statement is hoisted to the top. At that point all cow references within the function refer to the local variable cow, rather than the cow from the outer scope.
Solution 3:
Javascript does not have block scope (except in catch blocks).
All var statements are hoisted to the top of the containing function.
Therefore, cow refers to the local variable anywhere in the function, even if the if never executes.
Solution 4:
You didn't really read that article, did you? It explicitly states
Does
cowget turned into"glue"when you callf(2)? No,cowis safe in the above code because thevar cowdeclaration inside the if block applies to the entire function. It means thatcowis a local variable for the entire function.
However, when you remove the if block you also remove the variable declaration inside it, and the assignment will target the global variable.
Post a Comment for "Understanding Javascript Function Scoping"