ラベル callback の投稿を表示しています。 すべての投稿を表示
ラベル callback の投稿を表示しています。 すべての投稿を表示

2018年1月26日金曜日

JS functionの引数にfunctionを渡す使い方

1)コードを簡潔に記述できる
function putYourHeadInTheSand(otherFunc) {
    try{
         otherFunc();
    } catch(e) { } // ignore the error
}

....

putYourHeadInTheSand(function(){
    // do something here
});
putYourHeadInTheSand(function(){
    // do something else
});

2)callback、非同期になる
Lets say you load some data somehow. Rather than locking up the system waiting for it to load, you can load it in the background, and do something with the result when it arrives.
function loadStuff(callback) {
    // Go off and make an XHR or a web worker or somehow generate some data
    var data = ...;
    callback(data);
}

loadStuff(function(data){
    alert('Now we have the data');
});

3)Lazy loading
まだ理解できていない

参考:https://stackoverflow.com/questions/2824393/javascript-function-as-a-parameter-to-another-function