定義
if(1 > 0){
? ? document.write('a');
? ? document.write('b');
? ? document.write('c');
}
if(2 > 0){
? ? document.write('a');
? ? document.write('b');
? ? document.write('c');
}
if(3 > 0){
? ? document.write('a');
? ? document.write('b');
? ? document.write('c');
}
? ? ? 在js中這種重復(fù)叫偶合,這種偶合代碼叫低效代碼,編程講究一個原則:高內(nèi)聚、弱偶合,就是把相同功能的代碼抽取出來,放在一個盒子里邊,用的時候調(diào)用這個盒子就行了,這個盒子就是函數(shù)
函數(shù)聲明
function test() {
? ? document.write('a');
? ? document.write('b');
? ? document.write('c');
}
test();
function是個關(guān)鍵字,跟var差不多,后邊跟一個函數(shù)名,加個小括號,加個大括號,這就是函數(shù)。
? ? ? 把功能寫在函數(shù)里,用的時候調(diào)用一下就可以執(zhí)行,執(zhí)行方法就是:函數(shù)名(),比如上邊的代碼調(diào)用就是:test(),調(diào)用幾次就可以執(zhí)行幾次。
function test() {
? ? document.write('a');
? ? document.write('b');
? ? document.write('c');
}
if(1 > 0){
? ? test()
}
if(2 > 0){
? ? test()
}
if(3 > 0){
? ? test()
}
如果函數(shù)里的功能需要添加在條件里的話,就在函數(shù)外邊寫條件,符合條件調(diào)用一次函數(shù)就可以了
函數(shù)表達(dá)式
var test = function abc() {
}
var test = function () {
}
上邊是兩種函數(shù)表達(dá)式,第一種叫命名函數(shù)表達(dá)式,第二種叫匿名函數(shù)表達(dá)式,由于匿名函數(shù)表達(dá)式比較常用,這兩種表達(dá)式和變量差不多,調(diào)用的時候要調(diào)用變量名,這兩種表達(dá)式只有一個區(qū)別,命名函數(shù)表達(dá)式有name屬性,匿名表達(dá)式?jīng)]有。