JavaScript 匿名函数
这个周末我在网上读到了以下内容,我想知道大多数其他人是否认为这是正确(更好)的做事方式。
这不是最好(正确)的做事方式:
$(document).ready(function() { $('#magic').click(function(e) { $('#yayeffects').slideUp(function() { // ... }); }); $('#happiness').load(url + ' #unicorns', function() { // ... }); });
这更好:
var PI = { onReady : function() { $('#magic').click(PI.candyMtn); $('#happiness').load(PI.url + ' #unicorns', PI.unicornCb); }, candyMtn : function(e) { $('#yayeffects').slideUp(PI.slideCb); }, slideCb : function() { ... }, unicornCb : function() { ... } }; $(document).ready(PI.onReady);
一个人的表现比另一个人更好吗?更容易调试?
想法?评论?
I read the following on the web this weekend and I wanted to know if most others consider this the right (better) way of doing things.
This is not the best (right) way to do things:
$(document).ready(function() { $('#magic').click(function(e) { $('#yayeffects').slideUp(function() { // ... }); }); $('#happiness').load(url + ' #unicorns', function() { // ... }); });
That this is better:
var PI = { onReady : function() { $('#magic').click(PI.candyMtn); $('#happiness').load(PI.url + ' #unicorns', PI.unicornCb); }, candyMtn : function(e) { $('#yayeffects').slideUp(PI.slideCb); }, slideCb : function() { ... }, unicornCb : function() { ... } }; $(document).ready(PI.onReady);
Does one perform better than the next? Easier for debugging?
Thoughts? Comments?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的堆栈跟踪中包含大量匿名函数,则需要花费更多时间才能查明错误到底发生在哪里以及从哪里调用。所以第二个加 1。
事件处理程序内部的代码通常与注册处理程序的代码没有太大关系,因此应该位于单独的函数/模块中。第二个加 1。
对侦听器使用匿名函数也很糟糕,因为如果您必须删除此侦听器(大多数人不关心),您可以只删除它们,而不必担心意外地从代码的其他部分删除其他侦听器。第二个加 1。
将相关功能放入单个对象中并不一定是最好的。如果您将侦听器的行为用于不同的 dom 对象,则大多数情况下 onReady 函数都会很糟糕。
不关心性能。侦听器通常不会被频繁调用,因为它很重要。如果确实如此,则很可能在其他地方出现问题。
If you have a stacktrace with lots of anonymous functions in it it takes significantly more time to find out where the error exactly has happened and from where it was called. so plus 1 for second.
The code inside an event handler has often not much to do with the code where the handler gets registered and should therefore be in a separate function/module. plus 1 for second.
Using anonymous functions for listeners is also bad because in case you have to remove this listeners (which most people don't care about) you can remove only them and you don't have to care about accidentally removing other listeners form other parts of code. plus 1 for the second.
Put the related functions into a single object is not necessarily the best. Mostly the onReady function is bad if you use the behaviour of the listeners for different dom objects.
don't care about performance. a listener is usually not called that often that it matters.If it does, there is most likely a problem somewhere else.
第二种变体是可重用的 - 您可以为其他控件的其他事件重用 SlideCb 和其他处理程序。
The second variant is reusable - you can reuse slideCb and other handlers for other events for other controls.