What are the benefits to using anonymous functions instead of named functions for callbacks and parameters in JavaScript event code?

前端 未结 5 1641
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 06:51

I\'m new-ish to JavaScript. I understand many of the concepts of the language, I\'ve been reading up on the prototype inheritance model, and I\'m whetting my whistle with m

5条回答
  •  [愿得一人]
    2020-12-02 07:19

    A bit late to the party, but some not yet mentioned aspects to functions, anonymous or otherwise...

    Anon funcs are not easily referred to in humanoid conversations about code, amongst a team. E.g., "Joe, could you explain what the algorithm does, within that function. ... Which one? The 17th anonymous function within the fooApp function. ... No, not that one! The 17th one!"

    Anon funcs are anonymous to the debugger as well. (duh!) Therefore, the debugger stack trace will generally just show a question mark or similar, making it less useful when you have set multiple breakpoints. You hit the breakpoint, but find yourself scrolling the debug window up/down to figure out where the hell you are in your program, because hey, question mark function just doesn't do it!

    Concerns about polluting the global namespace are valid, but easily remedied by naming your functions as nodes within your own root object, like "myFooApp.happyFunc = function ( ... ) { ... }; ".

    Functions that are available in the global namespace, or as nodes in your root object like above, can be invoked from the debugger directly, during development and debug. E.g., at the console command line, do "myFooApp.happyFunc(42)". This is an extremely powerful ability that does not exist (natively) in compiled programming languages. Try that with an anon func.

    Anon funcs can be made more readable by assigning them to a var, and then passing the var as the callback (instead of inlining). E.g.: var funky = function ( ... ) { ... }; jQuery('#otis').click(funky);

    Using the above approach, you could potentially group several anon funcs at the top of the parental func, then below that, the meat of sequential statements becomes much tighter grouped, and easier to read.

提交回复
热议问题