Can a javascript anonymous function return itself?

374 views Asked by At

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?

1

There are 1 answers

0
Software Engineer On

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.