实际上,这是一个品味问题。对我来说,闭包是一种更明确、更“自然”的传递数据的方式。但是在某些情况下event.data
更方便,例如在循环中:
// doesn't do what you want!
for(var i = 0; i < 5; i++)
$("#button" + i).on("click", function(e) { alert("Button " + i + " clicked") });
// works just fine
for(var i = 0; i < 4; i++)
$("#button" + i).on("click", {i: i}, function(e) { alert("Button " + e.data.i + " clicked") });
另一个用例是单个函数充当多个对象的事件处理程序:
$("#add_button").on("click", {action: "+"}, calculatorButtonClicked);
$("#mul_button").on("click", {action: "*"}, calculatorButtonClicked);
$("#div_button").on("click", {action: "/"}, calculatorButtonClicked);
function calculatorButtonClicked(e) {
...lots of common code
switch(e.data.action) {
case '+': result = x + y;
case '*': result = x * y;
etc
}
...lots of common code
}