事件处理程序绑定到匿名函数vs命名函数 [英] Event handler bind to an anonymous function vs named function

查看:78
本文介绍了事件处理程序绑定到匿名函数vs命名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 .on()存在于jQuery .bind()不应该在将来使用,考虑到我有一个版本的jQuery大于或等于1.7。



我想知道的是:有没有使用 .bind()



将匿名函数或命名函数附加到事件处理程序之间的差异示例:

  //匿名函数
$(。 ).bind(click,function(){
alert(Hello);
});

//命名函数
$(。warning)。bind(click,foo);

function foo(){
alert(Hello);
}

想象一下,我有100个 div 在我的页面中的类警告。函数 .bind()将为每个具有匿名函数的处理程序附加一个新函数,但与JavaScript和jQuery内部的命名函数完全相同?



谢谢。

解决方案

不会有任何一个主要的区别是,使用命名功能,您还可以选择性地解除绑定功能,而不仅仅是与事件类型相关联的所有功能。



当然,这也可以帮助您避免代码重复。


I know .on() exists with jQuery and .bind() should not be used in the future, considering that I have a version of jQuery greater than or equal to 1.7.

What I want to know is this: are there are any differences between attaching an anonymous function or named function to an event handler using .bind()?

Example:

// Anonymous function
$(".warning").bind("click", function(){
   alert("Hello");
});

// Named function
$(".warning").bind("click", foo);

function foo(){
   alert("Hello");
}

Imagine that I have 100 div's with the class warning in my page. The function .bind() will attach a new function to every handler with an anonymous function but will it be exactly the same with a named function in the very internal of JavaScript and jQuery?

Thank you.

解决方案

There won't be any noticeable performance difference.

One main difference is that with a named function you can also selectively unbind functions and not just all functions associated with an event type.

Of course, this can also help you avoid code duplication.

这篇关于事件处理程序绑定到匿名函数vs命名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆