debugging 命名匿名函数

8zzbczxx  于 2022-11-14  发布在  其他
关注(0)|答案(6)|浏览(190)

有没有可能以某种方式为匿名函数设置一个名称?
对于匿名函数,不需要将函数名添加到命名空间中,但我希望避免在我的javascript调试器中看到大量的(?),这样我就可以保持调用堆栈跟踪信息。
我还能安全地传递普通的声明函数作为参数而不是匿名函数吗?或者我会不会走进一些奇怪的错误。它似乎起作用了。

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

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

[编辑]
我指的沿着像

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

f1tvaqid1#

第二个例子是使用一个 named function expression,它在大多数浏览器中都能正常工作,但在IE中有一些问题,在使用它之前应该注意。

k5hmc34c

k5hmc34c2#

你可以用箭头函数来做类似的事情,它对我在Node上很有效。

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

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

  return fn
}

MDN在这里有些误导:
您不能更改函数的名称,此属性是只读的...
要更改它,* 您可以使用**Object.defineProperty()**通过 *。
This answer provides more details.

uurity8g

uurity8g3#

使用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);
})();
4ioopgfo

4ioopgfo4#

我通常会这样做:$(“对象”).bind(“单击”,函数名(){ alert(“x”);});
别出什么问题。
一些主要图书馆鼓励这样做:
https://groups.google.com/forum/m/#!topic/firebug/MgnlqZ1bzX8
http://blog.getfirebug.com/2011/04/28/naming-anonymous-javascript-functions/

2o7dmzc5

2o7dmzc55#

如果dynamic函数名是问题.可以尝试以下操作:

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

tp5buhyn

tp5buhyn6#

匿名函数是一个没有名字的函数,它从定义它的地方执行。或者,你可以在使用它之前定义调试函数。

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

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

相关问题