我注意到建议use named functions when binding an event handler to a javascript event 。当我的函数需要传递 this
对象时,我该如何做到这一点?
例如,如何通过直接调用doFancyStuff
来替换下面的匿名函数:
$(document).on('change', 'input.fancy-textbox', function () {
doFancyStuff($(this));
});
function doFancyStuff($textbox) {
// fanciness
}
如果您指出我可能违反上述代码的其他约定,请加分。
<小时/>为了澄清,我想从多个地方调用示例中的 doFancyStuff()
方法,否则,我可以这样做:
$(document).on('change', 'input.fancy-textbox', doFancyStuff);
function doFancyStuff() {
var $textbox = $(this);
// fanciness
}
最佳答案
我想说这是一个意见问题。我认为这里使用匿名函数没有问题。如果这是唯一调用 doFancyStuff
的地方,您可以这样做:
$(document).on('change', 'input.fancy-textbox', doFancyStuff);
function doFancyStuff() {
// fanciness
var $textbox = $(this)
}
但是,如果从多个位置调用此函数并且您无法更改它的工作方式,则必须执行以下操作:
$(document).on('change', 'input.fancy-textbox', doFancyStuffFromEvent);
function doFancyStuffFromEvent() {
// fanciness
doFancyStuff($(this));
}
function doFancyStuff($textbox) {
// fanciness
}
这很困惑。
关于javascript - jQuery:将 $(this) 传递给命名函数事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9025294/