Do you name your Anonymous Function in a Function

2019-08-04 07:39发布

问题:

I'm using firebug here, and trying to write a blog post to demonstrate something just like these code.

// Unnamed Anonymous Function
var count1 = function () {
  var x = 0, f;
  f = function () {
    x = x + 1;
    return x;
  };
  return f;
};

// Named Anonymous Function
var count2 = function cf() {
  var x = 0, f;
  f = function ff() {
    x = x + 1;
    return x;
  };
  return f;
};

var c = count1();
console.log(count1); // function()
console.log(c); // function()

var d = count2();
console.log(count2); // cf()
console.log(d); // ff()

The point is, firebug logs Anonymous Functions as just function(), and even you click the link it navigates you to the script tab but sometimes in wrong position, your Anonymous Function isn't there.

But if you name it like cf() or ff() you can easily recall what function it is.

In this example the code is short, but if you work in large scale application, e.g. in ASP.net Web Form script resource, naming for function may somehow save your day when debug ?

P.S. I prefer Function Expression over Function Declaration.

回答1:

Named function expressions can be great for debugging, just be aware that they can cause problems with older versions of internet explorer, so be careful.

This article goes into all the details, but the short version is that NFEs in IE can wind up getting hoisted as though they were function declarations, causing you to have to clean up in ways you shouldn't have to:

  var f = (function(){
    var f, g;
    if (true) {
      f = function g(){};
    }
    else {
      f = function g(){};
    }
    // null `g`, so that it doesn't reference extraneous function any longer
    g = null;
    return f;
  })();