我想做与Get JavaScript function-object from its name as a string 相反吗?
也就是说,给定:
function foo()
{}
function bar(callback)
{
var name = ???; // how to get "foo" from callback?
}
bar(foo);
如何获取引用后面的函数名称?
我想做与Get JavaScript function-object from its name as a string 相反吗?
也就是说,给定:
function foo()
{}
function bar(callback)
{
var name = ???; // how to get "foo" from callback?
}
bar(foo);
如何获取引用后面的函数名称?
如果你不能使用myFunction.name
,那么你可以:
// 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
属性的现代浏览器(它们是否存在?)直接添加它:
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];
}
});
}
function bar(callback){
var name=callback.toString();
var reg=/function ([^\(]*)/;
return reg.exec(name)[1];
}
>>> function foo() { };
>>> bar(foo);
"foo"
>>> bar(function(){});
""
var x = function fooBar(){};
console.log(x.name);
// "fooBar"
您可以使用以下方法提取对象和函数名称:
function getFunctionName()
{
return (new Error()).stack.split('\n')[2].split(' ')[5];
}
例如:
function MyObject()
{
}
MyObject.prototype.hi = function hi()
{
console.log(getFunctionName());
};
var myObject = new MyObject();
myObject.hi(); // outputs "MyObject.hi"
尝试访问该.name
属性:
callback.name
如果您正在寻找特定对象事件的函数,这可能会有所帮助:
var a = document.form1
a.onsubmit.name
对我来说,只需稍作修改(在父级之前添加 \),这项工作:
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];
}
});
}