<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>What is hoisting in Javascript?</title>
<style type="text/css">
</style>
<script type="text/javascript">
var a = 1;
function b() {
alert("step 1 a = " + a);
a = 10; // step 2
alert("step 2 a = " + a);
return;
function a() {} // step 1
}
b();
alert(a);
</script>
</head>
<body>
</body>
</html>
[color=red][b]以上代码的执行顺序是;[/b][/color]
1、The global a is set to 1
2、b() is called
3、function a() {} is hoisted and creates a local variable a that masks the global a
4、The local a is set to 10 (overwriting the function a)
5、The global a (still 1) is alerted
function b alert order:
===》1. step 1 a = function a() {}
===》2. step 2 a = 10
===》3. 1
[color=red][b]Java 语言没有 Hoisting 的概念[/b][/color],看如下代码:
public class JavaHoistingTest {
public String myvar = "my value";
public void testHoisting(){
System.out.println(myvar); //output ---> my value is different with javascript undefined. 输出的是全局的变量的值。
String myvar = "my valued"; // and this line tips : The local variable myvar is never read. 定义的变量没有使用。
}
public static void main(String[] args) {
JavaHoistingTest hoisting = new JavaHoistingTest();
hoisting.testHoisting();
}
}
输出
my value
参考资料:
http://stackoverflow.com/questions/15311158/javascript-hoisting
http://hszy00232.blog.163.com/blog/static/43022753201131315817814/
http://www.programmerinterview.com/index.php/javascript/javascript-hoisting/
http://docstore.mik.ua/orelly/webprog/jscript/ch04_03.htm