Confused about hoisting

别说谁变了你拦得住时间么 提交于 2019-12-20 02:38:56

问题


consider these slightly two different versions of hoisting...

mylocation = "dublin" 
function outputPosition() {
    alert(mylocation);
    mylocation = "fingal" ;
    alert(mylocation);
}
outputPosition();

This will output "fingal" and then "fingal"

mylocation = "dublin" 
function outputPosition() {
    alert(mylocation);
    var mylocation = "fingal" ;
    alert(mylocation);
}
outputPosition();

This will output "undefined" and "fingal"

Why?


回答1:


Once you declare variable using var keyword within a javascript function and no matter where you put this declaration - at the top of the function or at the buttom, it will be considered as local variable. So that is why you get undefined when you try to get value of such variable before var declaration.




回答2:


In the second option, you hide mylocation (which I hope was declared in outer scope.) with a new variable via the var declaration.

"In JavaScript, variable can be declared after being used." meaning: JavaScript pulls up var declarations to the top of the scope(No matter where it was declared!), so in your second function var mylocation is implicitly defined but not assigned before the first alert, hence it output undefined at that point.




回答3:


The output of first snippet must be "dublin" and "fingal" provided that mylocation is defined,otherwise its a reference error.

For more details :

http://bustingseams.blogspot.in/2009/08/another-javascript-pitfall-hoisting.html




回答4:


In JavaScript - variable declarations are hoisted but initialization is not. That means that when you write var anywhere inside a function it will be treated as declared in top. So it will not take the same name variable from global space.

@Ashish is right, the first snippet should output "dublin" and "fingal".




回答5:


Take for example :

x = 5;
var x;

console.log( x );

Technically you might want to look at x = 5; as a wrong statement in this context considering the fact that it comes before the declaration, but the JS Engine doesn't work that way. It sees x = 5 and var x as two separate statements, the first one a compiler-related task, and the second one an execution-related task.

what this means in simple terms is that all declarations in a scope, regardless of where they appear, are processed first before the code itself is executed. i.e you can execute a variable before declaring it.



来源:https://stackoverflow.com/questions/9753373/confused-about-hoisting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!