私は自分の意見を述べるつもりであり、これがベスト プラクティスであると主張するつもりはありません。代わりに、名前付き関数への参照を常に引数として渡していました。回避できる場合は、小さなラッパーの無名関数を渡すことはありませんでした。しかし、私はこの基準から離れました。現在、関数の署名に反復があまりないと思われる場合は名前付き関数への参照を渡し、関数の署名に反復があると思われる場合はラッパーの無名関数を渡します。
このJS Fiddleを使用して、以前の標準、現在の標準、および古い標準から離れた理由を説明します。要約すると、いくつかのバグから、ラップされた無名関数を渡すと、関数に渡す引数を明示的にコーディングする必要があるため、より安全にリファクタリングできることを学びました。それでも、どちらのパターンにもそれぞれの場所があります。
var btn = document.getElementById('btn');
var btn2 = document.getElementById('btn2');
//I previously tended to pass in function name references. However, I recently moved towards
//passing in anonymous functions because I found that pattern to be a bit more refactor safe.
//More specifically, it is more refactor safe when you suspect the signature of our function
//will change. If you never expect the function's signature to change, then I guess you shouldn't
//need to worry about passing in an anonymous function.
//Because of the way addEventListener uses addNewItem, addNewItem will always receive one
//paramter: the event object. Therefore, we are not using addNewItem correct. It expects one
//argument that is message. Previously, we were calling addNewItem correctly when it looked like
//addNewItemOld and expected zero arguments. Click "Add message incorrect" to see the incorrect
//behaviour
btn.addEventListener("click", addNewItem);
//Now I often to wrap my function calls in anonymous functions because I know exactly what arguments
//I'm passing into my function. In this case I am explicitely not passing in a message. Now, we are
//using the addNewItem function correctly
btn2.addEventListener("click", function(e) { addNewItem(); });
//This function has been refactored. It used to look like addNewItemOld. The way
//this function's signature has been refactored is particularly interesting. It now
//has an optional paramter called message.
function addNewItem(message) {
var span =document.createTextNode(message || "Now nodes have a default message"),
workspace = document.getElementById("workspace");
workspace.appendChild(span);
}
function addNewItemOld() {
var span =document.createTextNode("Every node has the same message"),
workspace = document.getElementById("workspace");
workspace.appendChild(span);
}