简体   繁体   中英

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!"

您的警报语句会看到局部变量foobar并提醒其值,因为它在范围链上比window.foobar更高。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM