javascript作用域和作用域链
本文介绍了javascript作用域和作用域链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<script>
window.onload=function(){
var scope="global";
function t(){
console.log(scope);
var scope="local";
console.log(scope);
}
t();
}
</script>
</body>
</html>
上面的这一段代码,第一个打印的是undefined,第二个打印的是local,这是为什么啊,不是说通过作用域链可以向上访问的吗,那为什么第一次打印的时候会是undefined。
解决方案
不知道你看的哪本书,应该基本上都会讲到。
window.onload=function(){
var scope="global";
function t(){
console.log(scope);
var scope="local";
console.log(scope);
}
t();
}
这里是变量声明提前,修改后就是这样
function t(){
var scope;
console.log(scope);
scope = "local";
console.log(scope);
}
所以第一个.log输出是因为在自己的函数作用域链上找到了一个本地变量,但是此时还没有赋值-->undefined。
同理,第二个是因为已经赋值了--> local。
这篇关于javascript作用域和作用域链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文