a.作用域?qū)傩允窃诙x函數(shù)的時(shí)候決定的砸王,不是在調(diào)用函數(shù)的時(shí)候決定推盛。//JavaScript中的函數(shù)運(yùn)行在它們被定義的作用域里,而不是它們被執(zhí)行的作用域里
eg.
var name="lw";
function alert_1(){
? alert(name);
}
function alert_2(){
?var name="zgm";
?alert_1();
}
alert_2();//結(jié)果:lw
b.js的預(yù)編譯:
1.在一段js代碼執(zhí)行之前,會(huì)預(yù)先處理var關(guān)鍵字和function定義式(函數(shù)表達(dá)式和函數(shù)定義式)谦铃,對(duì)于局部變量耘成,變量的值會(huì)在真正執(zhí)行的時(shí)候計(jì)算。
2.函數(shù)定義注意:函數(shù)定義式和函數(shù)表達(dá)式的不同, 對(duì)于函數(shù)定義式, 會(huì)將函數(shù)定義提前.而函數(shù)表達(dá)式, 會(huì)在執(zhí)行過(guò)程中才計(jì)算。
eg.
alert(typeof hello);//結(jié)果:function
alert(typeof world);//結(jié)果:undefined
function hello(){//函數(shù)定義式
? ?alert("hello");
}
var world=function(){//函數(shù)表達(dá)式
? alert("world");
}
alert(typeof world);//結(jié)果:function
c.js預(yù)編譯是以段為處理單元
eg.
<script>
alert(typeof hello); //結(jié)果:undefined
</script>
<script>
function hello() {
?alert('hello world');
}
</script>
d.作用域鏈代碼優(yōu)化在標(biāo)識(shí)符解析的時(shí)候瘪菌,查找全局變量是最慢的撒会,所以盡量使用局部變量。
eg.
function changeColor(){ ?
? var doc=document; ?
doc.getElementById("NM").onclick=function(){ ? ? ? ? ? ? ? ? ? ? ? doc.getElementById("AL").style.backgroundColor="red"; ?
? };
}