より慣用的な方法は を使用するFunction.bind
ことであり、クロージャーを作成するためにコードを複製する必要はありません。簡単な例 (カスタム コードがないもの) を使用して説明します
/**
* Retrieves the content of a url asyunchronously
* The callback will be called with one parameter: the html retrieved
*/
function getUrl(url, callback) {
$.ajax({url: url, success: function(data) {
callback(data);
}})
}
// Now lets' call getUrl twice, specifying the same
// callback but a different id will be passed to each
function updateHtml(id, html) {
$('#' + id).html(html);
}
// By calling bind on the callback, updateHTML will be called with
// the parameters you passed to it, plus the parameters that are used
// when the callback is actually called (inside )
// The first parameter is the context (this) to use, since we don't care,
// I'm passing in window since it's the default context
getUrl('/get/something.html', updateHTML.bind(window, 'node1'));
// results in updateHTML('node1', 'response HTML here') being called
getUrl('/get/something-else.html', updateHTML.bind(window, 'node2'));
// results in updateHTML('node2', 'response HTML here') being called
Function.bind
は新しいので、下位サポートが必要な場合は、の互換性セクションを参照してください。 Function.bind
最後に、質問が jQuery としてタグ付けされていないことを知っています。これは、クロス ブラウザーの問題に対処せずに非同期関数を表示する最も簡単な方法でした。