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)
{
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];
}
});
}
var name = callback.name;
MDN:
The name property returns the name of a function, or an empty string for anonymous functions:
Live DEMO
try to access the .name
property:
callback.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];
};
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];
}
});
}
var x = function fooBar(){};
console.log(x.name);
// "fooBar"
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"