在Javascript中,Call Function絕對不會陌生,但如果有若干數量的Function因應不同的情況才Call怎麼辦呢?
當然有很多可能性,其中最常見的亦是傳統做法不外乎
if..(condition)..then...
function1();
function2();
function3();
...
而我的做法就是自行寫一個Helper,用Array以arguments型式去呼叫Function。
function SayGoodBye()
{
$('#hello').html('GoodBye');
}
function SeeYou()
{
$('#hello').html($('#hello').html() + ',' + 'See you next time!');
}
function caller(aryfunc)
{
$.each(aryfunc,function(i,n) //用jQuery的each
{ Function.call(n()); }
);
}
$(document).ready(function() {
//if..(condition)..then...
var myFunc = new Array(SayGoodBye,SeeYou); //and more...
caller(myFunc); //Print out : GoodBye,See you next time!
});
<div id="hello"></div>
這就可以把 condition 移至外部,用Helper去呼叫Function更加靈活。而且Array中的項目,Function的arguments不只是資料型態(String,Int...),更可以是function()吧。