Javascript Function Scoping and Hoisting: A Deeper Dive
Ben Cherry's article on Javascript Scoping and Hoisting introduces the concepts of function hoisting and variable scoping. To better understand their impact, let's delve into an intriguing example he provides:
var a = 1; function b() { a = 10; return; function a() {} } b(); alert(a);
Run this code, and you'll find that it alerts "1," which may seem puzzling.
Function hoisting is a crucial concept هنا، elevating function declarations to the start of their scope. This means that the code above is effectively rewritten as:
function b() { function a() {} a = 10; return; }
Oddly enough, the function within the function, a(), functions similarly to a variable declaration (var a = function () {};). Consider this:
var a = 1; function b() { var a = function () {}; a = 10; return; } b(); alert(a);
Both versions yield the exact same result.
Essentially, the code does this:
var a = 1; // Defines "a" in the global scope function b() { var a = function () {}; // Defines "a" in the local scope a = 10; // Overwrites the local variable "a" return; } b(); alert(a); // Alerts the global variable "a"
The key takeaway is that function hoisting and variable scoping interact to produce this behavior. The inner function creates a local variable a, while the function declaration itself elevates the function to the top. This ultimately leads to the globally defined a being unaffected by changes within the function.
The above is the detailed content of How Does JavaScript Function Hoisting and Scoping Affect Variable Overwriting?. For more information, please follow other related articles on the PHP Chinese website!