0

When binding event handlers, I've found the need to create a function, since it would need to be referenced twice; once initially, and once to the event binding:

// Define function
function doSomething(){...}

// Call function initially
doSomething();

// Pass function as the event handler
$("#theElement").on("click", doSomething);

But then I realized I could start doing this by passing a self-invoking anonymous function as the event handler and returning arguments.callee:

// Much cleaner!
$("#theElement").on("click", (function(){
    ...
    return arguments.callee;
})());

Assuming that I do not ever use this function outside of these two instances, is it an okay practice to do so?

Fillip Peyton
  • 3,637
  • 2
  • 32
  • 60
  • Which is easier to understand and maintain? That should be your prime directive. – Steve Wellens Nov 12 '14 at 22:19
  • Both are ok. it depends on you. how and what you need. – Siraj Hussain Nov 12 '14 at 22:20
  • 1
    Well, `arguments.callee` is deprecated, and forbidden in ECMAScript 5th Edition in Strict Mode, so it probably should be phased out at this point. (References: [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee), which links back here, to: "[Why was the `arguments.callee.caller` property deprecated in JavaScript?](http://stackoverflow.com/questions/103598/why-was-the-arguments-callee-caller-property-deprecated-in-javascript/235760#235760)") – David Thomas Nov 12 '14 at 22:26
  • That's a good point. I was reading into the function itself and saw the same thing. – Fillip Peyton Nov 12 '14 at 22:27

1 Answers1

1

Well, most people would just stick with the first block, because it is clear, simple, and idiomatic. The second block saves one line of code, but the cost is code that does something strange. If your code does something strange then a lot of readers are likely to misunderstand its behavior and any changes they make will be likely to introduce defects.

Software Engineer
  • 15,457
  • 7
  • 74
  • 102