How does naming an anonymous function in JavaScript make a difference?

后端 未结 4 606
北恋
北恋 2021-02-14 07:08

I am analyzing the following two urls from John Resig\'s site, but I am not understanding how giving a name to the anonymous function has made a difference.

My understan

4条回答
  •  余生分开走
    2021-02-14 07:41

    in the examples internally you can skip the additional access to the ninja object in #13

    anonymous closure (accessing object ninja is needed although we are already in that context):

    var ninja = { 
      yell: function(n){ 
        return n > 0 ? ninja.yell(n-1) + "a" : "hiy"; 
      } 
    };
    

    named closure can be called directly:

    var ninja = { 
      yell: function yell(n){ 
        return n > 0 ? yell(n-1) + "a" : "hiy"; 
      } 
    };
    

    another advantage is that named closures enable stacktracing:

    so assuming you do:

    (function fooBar() { console.log(brazl); })();
    // will create an error with "fooBar" in the stack trace instead of "anonymous function"
    

    EDIT: although it might look like overhead sometimes it helps debugging during development and for example YUICompressor and Closure Compiler can strip these names if they are not essentially needed

提交回复
热议问题