标签:style blog color io ar java sp div on
JavaScript是一种解释型语言,按照<script>块儿来预编译和执行。
JavaScript解释器在预编译阶段,先预声明变量,再预声明函数。在执行阶段,进行变量赋值,和函数执行。
预编译阶段,对于变量只进行预声明,并初始化值为undefined,在执行阶段才真正进行赋值。
1 alert(variableA); //undefined 2 var variableA = 2; 3 alert(variableA); //2 4 5 6 alert(funcA); //function funcA(){alert(‘I am funcA.‘)} 7 funcA(); //I am funcA. 8 function funcA(){ 9 alert(‘I am funcA.‘); 10 }
预编译预条件无关!
1 alert(variableA); //undefined 2 alert(funcA); //function funcA(){alert(‘I am funcA.‘)} 3 funcA(); //I am funcA 4 5 if(true){ 6 var variableA = 2; 7 8 }else{ 9 function funcA(){ 10 alert(‘I am funcA.‘); 11 } 12 } 13 alert(variableA); //2
JavaScript按照<script>代码块来预编译!
1 <script> 2 funcA(); //I am funcA too. 3 function funcA(){ 4 alert(‘I am funcA.‘); 5 } 6 function funcA(){ 7 alert(‘I am funcA too.‘); 8 } 9 </script>
1 <script> 2 funcA(); //I am funcA. 3 function funcA() { 4 alert(‘I am funcA.‘); 5 } 6 </script> 7 <script> 8 funcA(); //I am funcA too. 9 function funcA() { 10 alert(‘I am funcA too.‘); 11 } 12 </script>
先预声明变量,再预声明函数,因此,预编译阶段variableA函数覆盖了variableA变量。在执行阶段,variableA变量被赋值为2,
1 alert(variableA); //function variableA(){alert(‘I am variableA.‘)} 2 var variableA = 2; 3 function variableA(){ 4 alert(‘I am variableA.‘); 5 } 6 alert(variableA); //2
1 alert(variableA); //function variableA(){alert(‘I am variableA.‘)} 2 function variableA(){ 3 alert(‘I am variableA.‘); 4 } 5 var variableA = 2; 6 7 alert(variableA); //2
1 alert(variableA); //undefined 2 var variableA = function(){ 3 alert(‘I am variableA.‘); 4 } 5 alert(variableA); //function variableA(){alert(‘I am variableA.‘)}
1 alert(variableA); //undefined 2 var variableA = function variableA(){ 3 alert(‘I am variableA.‘); 4 } 5 6 alert(variableA); //function variableA(){alert(‘I am variableA.‘)}
标签:style blog color io ar java sp div on
原文地址:http://www.cnblogs.com/zhouwenhong/p/4027687.html