像这样 :
addEventHandler(document.getElementById('btnAdd'), "click", function()
{ addNewItem(); }, false);
代替 :
addEventHandler(document.getElementById('btnAdd'), "click", addNewItem, false);
我知道这与工作得更多的 javascript 解释器有关。但是怎么做?
像这样 :
addEventHandler(document.getElementById('btnAdd'), "click", function()
{ addNewItem(); }, false);
代替 :
addEventHandler(document.getElementById('btnAdd'), "click", addNewItem, false);
我知道这与工作得更多的 javascript 解释器有关。但是怎么做?
使用命名函数允许:
传递一个除了调用一个其他函数(根据您的示例)之外什么都不做的匿名函数只是臃肿 - 内联函数表达式的冗长同时仍然具有命名函数,这是两全其美的。
使用命名功能涉及:
因此,如果您不重用该函数,最好使用匿名函数而不是创建命名函数。
但是,如果您的代码正是您展示的代码,那么匿名函数就毫无意义。第二个代码的等效匿名等效项是什么
addEventHandler(document.getElementById('btnAdd'), "click", function() {
// addNewItem implementation
}, false);
如果你已经有一个命名函数,例如因为你重用它,那么不要使用匿名函数来包装它。
我将发表我的意见,而不是声称这是最佳实践。我过去总是将命名函数的引用作为参数传递,并且当我可以避免它时,我永远不会传递小型包装匿名函数。但是,我已经远离了这个标准。现在,当我怀疑我的函数签名没有太多迭代时,我传入对命名函数的引用,当我怀疑我的函数签名上存在迭代时,我传入包装匿名函数。
我将使用这个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);
}