javascript 命名匿名函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3854141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Naming an anonymous function
提问by Raynos
Is it possible to somehow set a name for anonymous functions?
是否可以以某种方式为匿名函数设置名称?
There is no need to add function names to the namespace for anonymous functions but I would like to avoid seeing a large amount of (?) in my javascript debugger so I can keep the call stack trace informative.
没有必要为匿名函数的命名空间添加函数名称,但我想避免在我的 javascript 调试器中看到大量的 (?),这样我就可以保持调用堆栈跟踪的信息量。
Also can I safely pass normal declared functions as arguments instead of anonymous functions or will I walk into some strange errors. It seems to work.
我也可以安全地将普通声明的函数作为参数而不是匿名函数传递,还是会遇到一些奇怪的错误。它似乎工作。
$("object").bind("click", function() { alert("x"); });
$("object").bind("click", function debuggingName() { alert("x"); });
[Edit]
[编辑]
I meant something along the likes of
我的意思是类似的东西
$("object").bind("click", function() { Function.Name = "debuggingName"; alert("x"); });
采纳答案by Tim Down
Your second example is using a named function expression, which works fine in most browsers but has some problems in IE that you should be aware of before using it. I recommend reading kangax's excellent article on this subject.
您的第二个示例是使用命名函数表达式,它在大多数浏览器中都可以正常工作,但在 IE 中存在一些问题,您在使用之前应该注意这些问题。我推荐阅读kangax 关于这个主题的优秀文章。
回答by Hyman Steam
You could do something like this with arrow functions, it works for me on Node.
你可以用箭头函数做这样的事情,它在 Node.js 上对我有用。
const createTask = ([name, type = 'default']) => {
const fn = () => { ... }
Object.defineProperty(fn, 'name', {
value: name,
configurable: true,
})
return fn
}
MDN is somewhat misleading here:
You cannot change the name of a function, this property is read-only...
To change it, you could use Object.defineProperty()though.
您不能更改函数的名称,此属性是只读的...
要改变它,你可以使用Object.defineProperty()虽然。
回答by DDRRSS
With ECMAScript2015 (ES2015, ES6) language specification, it is possible to do without the use of slow and unsafe evalfunction and without Object.definePropertymethod which both corrupts function object and does not work in some crucial aspects anyway.
使用 ECMAScript2015 (ES2015, ES6) 语言规范,可以不使用缓慢且不安全的eval函数,也可以不使用Object.defineProperty方法,该方法既破坏了函数对象,又在某些关键方面不起作用。
See, for example, this nameAndSelfBindfunction that is able to both name anonymous functions and renaming named functions, as well as binding their own bodies to themselves as thisand storing references to processed functions to be used in an outer scope (JSFiddle):
例如,请参阅这个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);
})();
回答by Andrew Luhring
I normally do: $("object").bind("click" , function name() { alert("x"); });
我通常这样做: $("object").bind("click" , function name() { alert("x"); });
and don't run into any problems.
并且不要遇到任何问题。
Doing so is encouraged in some of the major libraries:
一些主要图书馆鼓励这样做:
https://groups.google.com/forum/m/#!topic/firebug/MgnlqZ1bzX8
https://groups.google.com/forum/m/#!topic/firebug/MgnlqZ1bzX8
http://blog.getfirebug.com/2011/04/28/naming-anonymous-javascript-functions/
http://blog.getfirebug.com/2011/04/28/naming-anonymous-javascript-functions/
回答by Shai Ben-Yehuda
If dynamicfunction name is the issue. You can try this:
如果动态函数名称是问题。你可以试试这个:
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 })();
source: Nate Ferrero
资料来源:内特费雷罗
回答by Q_Mlilo
An anonymous function is a function without a name, it is executed from where it is defined. Alternatively, you can define the debugging function before using it.
匿名函数是没有名称的函数,它从定义的地方执行。或者,您可以在使用之前定义调试功能。
function debuggingName() {
alert("x");
}
$("object").bind("click", debuggingName);

