Why does triggering event result in endless loop?

Why does triggering event result in endless loop?

This test page illustrates a behavior that I did not expect.  

When an object triggers an event from a function that is a member of the object, and the event name is the same as the function name, then not only is the handler function called, but the function that triggered the event is called repeatedly.

If the event name and function name differ then this does not occur.

Am I doing something wrong or is this in fact intended behavior for some reason?

Here is a sample to demonstrate:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>WTF?</title>
  5. <style>
  6. .method {color: red;}
  7. .handled {color: blue;}
  8. </style>
  9. <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
  10. </head>
  11. <body>
  12. <script>
  13. var foo = {
  14. bar: function(otherEventName){
  15. $('body').append('<div class="method">bar method called<div>');
  16. $(this).trigger(otherEventName || 'bar');
  17. }
  18. };
  19. $(foo).on('bar doh', function(evt){
  20. $('body').append(
  21. '<div class="handled">' + 
  22. evt.type + ' event handled<div>'
  23. );
  24. });
  25. </script>
  26. <button onclick="foo.bar();">call foo.bar() and trigger 'bar' event</button>
  27. <button onclick="foo.bar('doh');">call foo.bar('doh') and trigger 'doh' event</button>
  28. <button onclick="$('.method, .handled').remove();">reset</button>
  29. </body>
  30. </html>