javascript中变量声明提升(Hoisting)的理解 ---What is hoisting in Javascript?

18 篇文章 0 订阅
10 篇文章 0 订阅

<!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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值