命名匿名函数

时间:2010-10-04 09:57:06

标签: javascript debugging anonymous-types

是否可以以某种方式为匿名函数设置名称?

没有必要为匿名函数的命名空间添加函数名称,但我想避免在我的javascript调试器中看到大量(?),这样我就可以保持调用堆栈跟踪信息。

我也可以安全地将正常声明的函数作为参数而不是匿名函数传递,或者我会遇到一些奇怪的错误。它似乎有效。

$("object").bind("click", function() { alert("x"); });

$("object").bind("click", function debuggingName() { alert("x"); });

[编辑]

我的意思是

$("object").bind("click", function() { Function.Name = "debuggingName"; alert("x"); });

6 个答案:

答案 0 :(得分:18)

你的第二个例子是使用命名函数表达式,它在大多数浏览器中都能正常工作,但在使用它之前你应该注意IE中的一些问题。我建议阅读kangax's excellent article on this subject

答案 1 :(得分:1)

您可以使用箭头功能执行类似的操作,它在Node上对我有用。

const createTask = ([name, type = 'default']) => {
  const fn = () => { ... }

  Object.defineProperty(fn, 'name', {
    value: name,
    configurable: true,
  })

  return fn
}

MDN is somewhat misleading here:

  

您无法更改函数名称,此属性为只读...

     

要更改它,您可以使用 Object.defineProperty()

This answer provides more details.

答案 2 :(得分:0)

我通常这样做:     $( “对象”)。绑定( “点击”       ,function name(){           警报( “X”);     });

并且不会遇到任何问题。

在一些主要的图书馆鼓励这样做:

https://groups.google.com/forum/m/#!topic/firebug/MgnlqZ1bzX8

http://blog.getfirebug.com/2011/04/28/naming-anonymous-javascript-functions/

答案 3 :(得分:0)

如果动态功能名称是问题。你可以试试这个:

function renameFunction(name, fn) {
    return (new Function("return function (call) { return function " + name +
       " () { return call(this, arguments) }; };")())(Function.apply.bind(fn));
} 

renameFunction('dynamicName',function() { debugger })();

来源:Nate Ferrero How to dynamically set a function/object name in Javascript as it is displayed in Chrome

答案 4 :(得分:0)

使用ECMAScript2015(ES2015,ES6)语言规范,可以不使用缓慢且不安全的 eval 函数,而无需使用 Object.defineProperty 方法既破坏函数对象,又在某些关键方面不起作用。

例如,参见此nameAndSelfBind函数,该函数既可以命名匿名函数又可以重命名命名函数,还可以将自己的主体绑定为 this 并存储对在外部范围(JSFiddle)中使用的已处理函数:

(function()
{
  // an optional constant to store references to all named and bound functions:
  const arrayOfFormerlyAnonymousFunctions = [],
        removeEventListenerAfterDelay = 3000; // an auxiliary variable for setTimeout

  // this function both names argument function and makes it self-aware,
  // binding it to itself; useful e.g. for event listeners which then will be able
  // self-remove from within an anonymous functions they use as callbacks:
  function nameAndSelfBind(functionToNameAndSelfBind,
                           name = 'namedAndBoundFunction', // optional
                           outerScopeReference)            // optional
  {
    const functionAsObject = {
                                [name]()
                                {
                                  return binder(...arguments);
                                }
                             },
          namedAndBoundFunction = functionAsObject[name];

    // if no arbitrary-naming functionality is required, then the constants above are
    // not needed, and the following function should be just "var namedAndBoundFunction = ":
    var binder = function() 
    { 
      return functionToNameAndSelfBind.bind(namedAndBoundFunction, ...arguments)();
    }

    // this optional functionality allows to assign the function to a outer scope variable
    // if can not be done otherwise; useful for example for the ability to remove event
    // listeners from the outer scope:
    if (typeof outerScopeReference !== 'undefined')
    {
      if (outerScopeReference instanceof Array)
      {
        outerScopeReference.push(namedAndBoundFunction);
      }
      else
      {
        outerScopeReference = namedAndBoundFunction;
      }
    }
    return namedAndBoundFunction;
  }

  // removeEventListener callback can not remove the listener if the callback is an anonymous
  // function, but thanks to the nameAndSelfBind function it is now possible; this listener
  // removes itself right after the first time being triggered:
  document.addEventListener("visibilitychange", nameAndSelfBind(function(e)
  {
    e.target.removeEventListener('visibilitychange', this, false);
    console.log('\nEvent listener 1 triggered:', e, '\nthis: ', this,
                '\n\nremoveEventListener 1 was called; if "this" value was correct, "'
                + e.type + '"" event will not listened to any more');
  }, undefined, arrayOfFormerlyAnonymousFunctions), false);

  // to prove that deanonymized functions -- even when they have the same 'namedAndBoundFunction'
  // name -- belong to different scopes and hence removing one does not mean removing another,
  // a different event listener is added:
  document.addEventListener("visibilitychange", nameAndSelfBind(function(e)
  {
    console.log('\nEvent listener 2 triggered:', e, '\nthis: ', this);
  }, undefined, arrayOfFormerlyAnonymousFunctions), false);

  // to check that arrayOfFormerlyAnonymousFunctions constant does keep a valid reference to
  // formerly anonymous callback function of one of the event listeners, an attempt to remove
  // it is made:
  setTimeout(function(delay)
  {
    document.removeEventListener('visibilitychange',
             arrayOfFormerlyAnonymousFunctions[arrayOfFormerlyAnonymousFunctions.length - 1],
             false);
    console.log('\nAfter ' + delay + 'ms, an event listener 2 was removed;  if reference in '
                + 'arrayOfFormerlyAnonymousFunctions value was correct, the event will not '
                + 'be listened to any more', arrayOfFormerlyAnonymousFunctions);
  }, removeEventListenerAfterDelay, removeEventListenerAfterDelay);
})();

答案 5 :(得分:-3)

匿名函数是一个没有名称的函数,它是从定义它的位置执行的。或者,您可以在使用之前定义调试功能。

function debuggingName() { 
    alert("x"); 
}

$("object").bind("click", debuggingName);