//“赋值式”函数定义
Fn2();
var Fn2 = function(){
alert("Hello wild!");
}
Firebug报错:Fn2 is not a function,浏览器未对Fn2进行预处理,依序执行,所以报错Fn2未定义。
[b]3. 代码块及js文件的处理
[/b]“代码块”是指一对<script type=”text/javascript”></script>标签包裹着的js代码,文件就是指文件啦,废话:D
浏览器对每个块或文件进行独立的扫描,然后对全局的代码进行顺序执行(2中讲到了)。所以,在一个块(文件)中,函数可以在调用之后进行“定义式”定义;但在两个块中,定义函数所在的块必须在函数被调用的块之前。
很绕口,看例子好了:
//html head...
<script type="text/javascript">
function fnOnLoad(){
alert("I am outside the Wall!");
}
</script>
<body onload="fnOnLoad();">
<script type="text/javascript">
alert("I am inside the Wall..");
</script>
</body>
//先弹出“I am inside the Wall..”;
//后弹出“I am outside the Wall!”
function fn1(){
var sum = 0;
for(var ind=0; ind<1000; ind++) {
sum += ind;
}
alert("答案是"+sum);
}
function fn2(){
alert("早知道了,我就是不说");
}
fn1();
fn2();
//先弹出:“答案是499500”,
//后弹出:“早知道了,我就是不说”