javascript预编译练习(变态篇)
例1、
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> global = 100 function fn(){ console.log(global); global = 200; console.log(global); var global = 300 } fn() var global; </script> </body> </html>
执行分析
先生成GO{}
GO{
global:100
fn:function(){}
}
函数fn执行前生成AO{}
AO{
global:undefined
}
AO中有自己的变量global,不调用GO的global。(就近原则)
执行结果

例2
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
function test(){
console.log(b)
if(a){
var b = 100;
}
c = 234;
console.log(c);
}
var a;
test();
a = 10;
console.log(c);
</script>
</body>
</html>
执行分析
首先生成GO
GO{
a:undefined
test:function test(){}
}
执行test()行时生成AO{} 不要受 if 的影响。
AO{
b:undefined
}
//第一个输出为undefinded
接着执行if()模块
此时a为undefined,if()模块为false
接着GO{}中添加一个属性c,值为234
第二个输出为234 第三个输出是234.
执行结果

例3(百度2013笔试题
1)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
function bar(){
return foo;
foo = 10;
function foo(){
}
var foo = 11;
}
document.write(bar())
</script>
</body>
</html>
2)
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script type="text/javascript"> function bar(){ foo = 10; function foo(){ } var foo = 11; return foo; } document.write(bar()) </script> </body> </html>
1)的预编译分析
执行bar()生成一个AO对象 bar(){}函数中有var foo = 11,即有变量声明foo,值为undefined, 接着有函数function foo(){} ,foo的值被覆盖 为functoin(){}
AO{
foo:undefined ---> foo:function(){}
}
执行结果

2)的预编译分析
同上,最后foo的值被覆盖为11 并return。
执行结果


浙公网安备 33010602011771号