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

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

问题描述

我在这里使用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窗体脚本资源中,为函数命名可能会在调试时节省您的时间?

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.我更喜欢函数表达式而不是函数声明.

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可以绕线就像它们是函数声明一样被吊起,导致您不得不以不必要的方式进行清理:

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天全站免登陆