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

前端 未结 5 1648
伪装坚强ぢ
伪装坚强ぢ 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 06:58

    Its more readable using named functions and they are also capable of self-referencing as in the example below.

    (function recursion(iteration){
        if (iteration > 0) {
          console.log(iteration);
          recursion(--iteration);
        } else {
          console.log('done');
        }
    })(20);
    
    console.log('recursion defined? ' + (typeof recursion === 'function'));
    

    http://jsfiddle.net/Yq2WD/

    This is nice when you want to have an immediately invoked function that references itself but does not add to the global namespace. It's still readable but not polluting. Have your cake and eat it to.

    Hi, my name is Jason OR hi, my name is ???? you pick.

提交回复
热议问题