I want to do the opposite of Get JavaScript function-object from its name as a string?
That is, given:
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?
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];
};
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];
}
});
}
function bar(callback){
var name=callback.toString();
var reg=/function ([^\(]*)/;
return reg.exec(name)[1];
}
>>> function foo() { };
>>> bar(foo);
"foo"
>>> bar(function(){});
""
You can extract the object and function name with:
function getFunctionName()
{
return (new Error()).stack.split('\n')[2].split(' ')[5];
}
For example:
function MyObject()
{
}
MyObject.prototype.hi = function hi()
{
console.log(getFunctionName());
};
var myObject = new MyObject();
myObject.hi(); // outputs "MyObject.hi"
var x = function fooBar(){};
console.log(x.name);
// "fooBar"
尝试访问.name
属性:
callback.name
If you were looking for the function on an specific object event, this may help:
var a = document.form1
a.onsubmit.name
for me, with just a little modification (adding \\ before parent), this work:
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];
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.