你在函数表达式中命名你的匿名函数吗? [英] Do you name your Anonymous Function in a Function Expression?

查看:23
本文介绍了你在函数表达式中命名你的匿名函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里使用了 firebug,并试图写一篇博文来演示类似这些代码的东西.

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()

关键是,firebug 将匿名函数记录为 function(),即使您单击链接,它也会将您导航到脚本选项卡,但有时位置错误,您的匿名功能不存在.

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.

但是如果你把它命名为 cf()ff() 你可以很容易地回忆起它是什么函数.

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

在这个例子中,代码很短,但如果你在大型应用程序中工作,例如在 ASP.net Web Form 脚本资源中,为函数命名可能会以某种方式节省调试时间?

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.

推荐答案

命名函数表达式非常适合调试,但要注意它们可能会导致旧版本的 Internet Explorer 出现问题,所以要小心.

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.

这篇文章 详细介绍了所有细节,但简短的版本是 IE 中的 NFE 可以绕up 就像函数声明一样被提升,导致您必须以不应该的方式进行清理:

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;
  })();

这篇关于你在函数表达式中命名你的匿名函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆