JavaScript: If var statements are executed first, then why does this not work?
I tried the following in JavaScript (Firefox 3.5, Windows 开发者_运维百科XP):
(function(){
window.foobar = 'Welcome!';
})();
var foobar = 'PWN3D!';
alert(foobar);
The output was 'PWN3D!'. Why did my code PWN me? I thought var name = value;
executed first.
From the specification (page 87):
A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.
So the var
causes the variable to be created first, but the value ('PWN3D!'
) is assigned to it in the normal execution order.
I'm not sure what you mean by var
statements being executed first. The code you have written looks to be working exactly as I would have expected:
- An anonymous function is created
- The anonymous function is executed, which sets
foobar
to "Welcome!" - The
foobar
variable is set to "PWN3D!" - An alert box is raised with the current value of
foobar
, "PWN3D!"
Your alert statement sees the local variable, foobar and alerts its value as it is higher on the scope chain than window.foobar.
精彩评论