从Javascript函数引用中获取名称String? [英] Get name as String from a Javascript function reference?
本文介绍了从Javascript函数引用中获取名称String?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想反对获取JavaScript函数对象从其名称作为字符串?
即给定:
function foo()
{}
function bar(callback)
{
var name = ???; // how to get "foo" from callback?
}
bar(foo);
如何获取参考后面的函数名称?
How do I get the name of the function behind a reference?
推荐答案
如果你不能使用 myFunction.name
然后你可以:
If you can't use myFunction.name
then you can:
// Add a new method available on all function values
Function.prototype.getName = function(){
// Find zero or more non-paren chars after the function start
return /function ([^(]*)/.exec( this+"" )[1];
};
或者对于不支持 name
属性的现代浏览器(它们是否存在?)直接添加:
Or for modern browsers that don't support the name
property (do they exist?) add it directly:
if (Function.prototype.name === undefined){
// Add a custom property to all function values
// that actually invokes a method to get the value
Object.defineProperty(Function.prototype,'name',{
get:function(){
return /function ([^(]*)/.exec( this+"" )[1];
}
});
}
这篇关于从Javascript函数引用中获取名称String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文