到处绑定匿名函数
我通常编写如下所示的代码(但具有更多处理程序)。
$(document).ready(function() {
$("#next").click(function() {
doStuff();
});
$("#prev").click(function() {
doSomeOtherStuff();
});
$("#link").hover(function() {
doSomeTotallyOtherStuff();
});
});
这是最好的方法吗?我应该采取不同的做法吗? Paul Irish 的演示表明这是一个坏主意。这是真的吗?
I generally write code that looks like this (but with many more handlers).
$(document).ready(function() {
$("#next").click(function() {
doStuff();
});
$("#prev").click(function() {
doSomeOtherStuff();
});
$("#link").hover(function() {
doSomeTotallyOtherStuff();
});
});
Is this the best way of doing this? Should I do it differently? Paul Irish's presentation suggests it's a bad idea. Is that true?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我们喜欢使用对象字面量模式和命名函数。我会这样重写你的例子:
为什么?嗯,它使得在其他地方重用事件处理程序变得更容易,而无需求助于触发器。函数的命名可以帮助自我记录您的代码。测试/调试更容易。对象字面量仅向全局命名空间添加一个条目,因此与页面可能使用的其他脚本发生冲突的可能性很小。
We like to use the object literal pattern and named functions. I'd rewrite your example like this:
Why? Well, it makes it easier to reuse event handlers in other places without resorting to triggers. The naming of the function can help self-document your code. Testing/debugging is easier. The object literal only adds one entry to the global namespace, so there is little chance for collisions with other scripts your page might be using.
以旧的无聊方式定义函数很有用的原因之一是您可以在堆栈跟踪中查看名称。
在函数表达式中使用函数名是不安全的:
这有点不幸,但就是这样。
One reason that it's useful to define your functions the old boring way is that you get names to look at in stack traces.
It's not safe to use a function name in a function expression:
which is sort-of unfortunate but there you go.
只要您不在循环或其他运行多次的代码(即重复的函数调用)中执行此操作,这应该没问题。否则,一个匿名函数和一个命名函数之间没有太大区别。当你有 100 个相同的匿名函数时就会出现问题。
ex:
可以,
但不行,因为您创建了 100 个匿名函数而不是一个命名函数。
当然,编辑
,如果您将单个函数调用包装在闭包中,那么您就做错了,您可以只传递函数本身。
This should be fine as long you don't do it in a loop or some other code that runs more than once (i.e. a recurring function call). Otherwise there's not much difference between one anon function and one named function. it's when you have 100 identical anonymous functions that's a problem.
ex:
is okay,
is not, because you've created 100 anonymous functions instead of one named function.
EDIT
of course, if you're wrapping a single function call in a closure, you're doing it wrong, you can just pass the function itself.