How to get the function name from within that function?
Asked Answered
C

22

346

How can I access a function name from inside that function?

// parasitic inheritance
var ns.parent.child = function() {
  var parent = new ns.parent();
  parent.newFunc = function() {

  }
  return parent;
}

var ns.parent = function() {
  // at this point, i want to know who the child is that called the parent
  // ie
}

var obj = new ns.parent.child();
Courtyard answered 15/4, 2010 at 19:19 Comment(13)
well, in the parent, i can then access other functions by convention, such as ns[child][schema] or ns[child][dbService]. Without it, I have to hard code these references in every child class.Courtyard
why not just pass the child function as an argument to the parent? var parent = new ns.parent(this);Fresh
because there are dozens of such lookups, and dozens of children. That is currently what I'm doing, but it's the same every time and would be perfect if that duplicate logic could simply be placed inside the parent once, based on the derived function.Courtyard
see, it's not the child function I want, it's the naming convention used, because that naming convention can be used to load other functions that are not currently defined on the child object, but are related to that child throughout the system.Courtyard
ie, app.schemas.child = { } which is defined in another file and not present on the child object.Courtyard
@Scott var ns.parent.child - this code is invalidDiverticulitis
@Scott, there is a lot going on here. Why do you need a reference back to the caller? Would it not be easier to send the reference while making the call?Felske
what would you return if your function was defined as foo = bar = function() { return function_name(); }?Electricity
@Scott I agree with everyone else, your managing your complexity and code structure wrong to need to do this. This kind of hard-coupling is a bad design decision and is going to make a mess. @SimeVidas your a great necromancer :)Immodest
It strikes me has something odd, because if I do something like var test2 = test; What is the name of the function now?Dabber
Possible duplicate of Can I get the name of the currently running function in JavaScript?Matthiew
Does this answer your question? Get current function name in strict modeMatthiew
It depends on lexical scope, you may find it by playing a little bit in this way arguments.callee.caller ... .nameJoanajoane
B
214

In ES6, you can just use myFunction.name.

Note: Beware that some JS minifiers might throw away function names, to compress better; you may need to tweak their settings to avoid that.

In ES5, the best thing to do is:

function functionName(fun) {
  var ret = fun.toString();
  ret = ret.substr('function '.length);
  ret = ret.substr(0, ret.indexOf('('));
  return ret;
}

Using Function.caller is non-standard. Function.caller and arguments.callee are both forbidden in strict mode.

Edit: nus's regex based answer below achieves the same thing, but has better performance!

Bromism answered 30/3, 2013 at 2:59 Comment(8)
While this didn't answer the question sufficiently for me (due to anonymous functions), it did give me idea to do this: fun.toString().substr(0, 100) which for my needs will be enough to locate the function in question. So, thanks for the inspiration!Pfaff
Nice, ES6 myFunction.name is perfect. Is this a preferred thing to do in ES6?Wintergreen
Yup myFunction.name is the best thing to do in ES6.Bromism
NB. myFunction.name also works with ES6 arrow functions (usually anonymous), if you assign them in an expression (e.g. const myNamedFunction = () => { ...};). Thanks @hughfdjackson: https://mcmap.net/q/94239/-how-do-i-write-a-named-arrow-function-in-es2015Elanaeland
What's the point in myFunction.name if you type the function name? defeats the purpose of magic variables.Taxis
@adi518: not necessarily .. suppose you have any array of functions and you iterating over it, using for/foreach ..then arr[index].name will also work :)Mace
Or maybe even fun.toString().split('(')[0].split(' ')[1] or even shorter fun.toString().split(/[\(\s]/)[1]Eupheemia
@Taxis It's not useless. If I'm renaming the function within my IDE, myFunction.name will also be updated. Sure, intelliJ supports renaming identifiers within strings, but that works a lot less consistently and will silently become outdated if somebody forgets to tick the "search in strings" option. myFunction.name is a slightly better choice than hardcoding the string.Pearson
O
185

ES6 (inspired by sendy halim's answer below):

myFunction.name

Explanation on MDN. As of 2015 works in nodejs and all major browsers except IE.

Note: On bound functions this will give "bound <originalName>". You will have to strip the "bound " if you want to get the original name.


ES5 (inspired by Vlad's answer):

If you have a reference to the function, you can do:

function functionName( func )
{
    // Match:
    // - ^          the beginning of the string
    // - function   the word 'function'
    // - \s+        at least some white space
    // - ([\w\$]+)  capture one or more valid JavaScript identifier characters
    // - \s*        optionally followed by white space (in theory there won't be any here,
    //              so if performance is an issue this can be omitted[1]
    // - \(         followed by an opening brace
    //
    var result = /^function\s+([\w\$]+)\s*\(/.exec( func.toString() )

    return  result  ?  result[ 1 ]  :  '' // for an anonymous function there won't be a match
}
  • I have not run unit tests on this, or verified implementation differences, but in principle it should work, if not leave a comment.
  • Note: won't work on bound functions
  • Note: that caller and callee are considered deprecated.

[1] I include it here because it is legal and often enough syntax highlighting tools fail to take into account the white space between function name and parenthesis. On the other hand, I'm not aware of any implementation of .toString() that will include white space here, so that's why you can omit it.


As an answer to the original question, I would drop parasitic inheritance and go for some more traditional OOP design patterns. I wrote a TidBits.OoJs to comfortably write OOP code in JavaScript with a feature set mimicking C++ (not yet complete, but mostly).

I see from the comments that you would like to avoid passing information parent needs to it's constructor. I must admit that traditional design patterns won't save you from that one though, since it is generally a considered a good thing to make your dependencies obvious and enforced.

I would also suggest to steer away from anonymous functions. They only make debugging and profiling a PITA because everything just shows up as "anonymous function", and there is no benefit to them that I'm aware of.

Odessaodetta answered 29/7, 2013 at 12:13 Comment(4)
Nice RegEx! Here's a performance test showing that your code is the fastest in many cases. In general it seems that RegEx beats native JS by around 2x speed here on average. jsperf.com/get-function-name/2Mortality
@Tomasz Hi, thanks for pointing that out. I didn't know that. A bound function is actually a new function that wraps your original function. The ecmascript standard § 19.2.3.2 defines that the name of the new function shall be "bound" + originalName. The toString method won't work on bound functions either... You will have to strip the word bound.Odessaodetta
What's the point in myFunction.name if you type the function name? defeats the purpose of magic variables.Bullyboy
Note that if you're using React Native this may not work properly. I have a RN project I'm working on with expo version 36 and a component method's .name property was showing up as the string "value", no matter what it was called. Weirdly enough, while testing in the expo app it was fine, however, once compiled into a real application, it would crash silently.Aureolin
C
89

what you're doing is assigning unnamed function to a variable. you probably need named function expression instead ( http://kangax.github.com/nfe/ ).

var x = function x() {
    console.log( arguments.callee.name );
}
x();

however I'm not sure how much cross-browser that is; there's an issue with IE6 that makes you function's name leak to the outer scope. also, arguments.callee is kind of deprecated and will result in error if you're using strict mode.

Chickie answered 3/4, 2011 at 20:51 Comment(2)
This doesn't works on old versions of Safari browser.Elevation
arguments.callee is forbidden in strict mode, but who cares--> plus one.Fishhook
D
27

It looks like the most stupid thing, that I wrote in my life, but it's funny :D

function getName(d){
  const error = new Error();
  const firefoxMatch = (error.stack.split('\n')[0 + d].match(/^.*(?=@)/) || [])[0];
  const chromeMatch = ((((error.stack.split('at ') || [])[1 + d] || '').match(/(^|\.| <| )(.*[^(<])( \()/) || [])[2] || '').split('.').pop();
  const safariMatch = error.stack.split('\n')[0 + d];

  // firefoxMatch ? console.log('firefoxMatch', firefoxMatch) : void 0;
  // chromeMatch ? console.log('chromeMatch', chromeMatch) : void 0;
  // safariMatch ? console.log('safariMatch', safariMatch) : void 0;
  
  return firefoxMatch || chromeMatch || safariMatch;
}

d - depth of stack. 0 - return this function name, 1 - parent, etc.;
[0 + d] - just for understanding - what happens;
firefoxMatch - works for safari, but I had really a little time for testing, because mac's owner had returned after smoking, and drove me away :'(

Testing:

function limbo(){
  for(let i = 0; i < 4; i++){
    console.log(getName(i));
  }
}
function lust(){
  limbo();
}
function gluttony(){
  lust();
}

gluttony();

Result:
Chrome:
enter image description here

Fitefox:
enter image description here

This solution was creating only just for fun! Don't use it for real projects. It does not depend on ES specification, it depends only on browser realization. After the next chrome/firefox/safari update it may be broken.
More than that there is no error (ha) processing - if d will be more than stack length - you will get an error;
For other browsers error's message pattern - you will get an error;
It must work for ES6 classes (.split('.').pop()), but you sill can get an error;

Dovap answered 14/12, 2017 at 11:54 Comment(2)
It is similar to It is similar to answer #38435950Matthiew
That is some intense choice of function name :pAnamariaanamnesis
T
23

Any constructor exposes a property name, which is the function name. You access the constructor via an instance (using new) or a prototype:

function Person() {
  console.log(this.constructor.name); //Person
}

var p = new Person();
console.log(p.constructor.name); //Person

console.log(Person.prototype.constructor.name);  //Person
Troublesome answered 10/8, 2015 at 17:25 Comment(2)
The first console.log call logs window or Object for me depending where I run it, not Person.Ponce
Are you sure you instantiated using "new"? Otherwise it cannot work.Troublesome
S
18

This might work for you:

function foo() { bar(); }

function bar() { console.log(bar.caller.name); }

running foo() will output "foo" or undefined if you call from an anonymous function.

It works with constructors too, in which case it would output the name of the calling constructor (eg "Foo").

More info here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Caller

They claim it's non-standard, but also that it's supported by all major browsers: Firefox, Safari, Chrome, Opera and IE.

Supersensible answered 3/4, 2011 at 19:59 Comment(1)
Not available in strict mode...mmmVeld
H
11

You could use this, for browsers that support Error.stack (not nearly all, probably)

function WriteSomeShitOut(){ 
  var a = new Error().stack.match(/at (.*?) /);
  console.log(a[1]);
} 
WriteSomeShitOut();

of course this is for the current function, but you get the idea.

happy drooling while you code

Hauteur answered 13/12, 2014 at 18:15 Comment(2)
plus one for the funny function name :DCameliacamella
It is similar to answer #38435950Matthiew
F
10

You can't. Functions don't have names according to the standard (though mozilla has such an attribute) - they can only be assigned to variables with names.

Also your comment:

// access fully qualified name (ie "my.namespace.myFunc")

is inside the function my.namespace.myFunc.getFn

What you can do is return the constructor of an object created by new

So you could say

var obj = new my.namespace.myFunc();
console.info(obj.constructor); //my.namespace.myFunc
Fresh answered 15/4, 2010 at 19:27 Comment(4)
i need it inside the func because i'm passing it up the inheritance chain and I omitted that stuff for brevity.Courtyard
'this' will be the instance that invoked the function. So if you 'this' inside the parent function that will give you the instance of the function that called it. That's all you should need - not sure why you need the name tooFresh
well, in the parent, i can then access other functions by convention, such as ns[child][schema] or ns[child][dbService]. Without it, I have to hard code these references in every child class.Courtyard
my use case for finding the name is to make it easier for constructing console.error messages that tell where the message came from without having to revert to the stack dump. e.g. console.error({'error':{self.name reference} + " error with input parameter"). It becomes much easier to cut/paste error messages that repeat in multiple functions if you don't have to stop and change text within them each time. In my case, I'm returning promise errors from multiple promise calls - nice to know what promise/function generated the error.Ease
S
8

You could use Function.name:

In most implementations of JavaScript, once you have your constructor's reference in scope, you can get its string name from its name property (e.g. Function.name, or Object.constructor.name

You could use Function.callee:

The native arguments.caller method has been deprecated, but most browsers support Function.caller, which will return the actual invoking object (its body of code): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fcaller

You could create a source map:

If what you need is the literal function signature (the "name" of it) and not the object itself, you might have to resort to something a little more customized, like creating an array reference of the API string values you'll need to access frequently. You can map them together using Object.keys() and your array of strings

Sherman answered 19/6, 2013 at 21:45 Comment(0)
A
7

You can use name property to get the function name, unless you're using an anonymous function

For example:

var Person = function Person () {
  this.someMethod = function () {};
};

Person.prototype.getSomeMethodName = function () {
  return this.someMethod.name;
};

var p = new Person();
// will return "", because someMethod is assigned with anonymous function
console.log(p.getSomeMethodName());

now let's try with named function

var Person = function Person () {
  this.someMethod = function someMethod() {};
};

now you can use

// will return "someMethod"
p.getSomeMethodName()
Ables answered 10/10, 2014 at 15:52 Comment(0)
L
6

You can use constructor name like:

{your_function}.prototype.constructor.name

this code simply return name of a method.

Legere answered 12/8, 2018 at 6:38 Comment(0)
H
5

as part as ECMAScript 6 you can use Function.name method

function doSomething() {}

alert(doSomething.name); // alerts "doSomething"
Hilliard answered 25/2, 2015 at 20:0 Comment(2)
In ReactJS you need to add this: console.log(this.doSomething.name);Pimply
that is outside the functionEase
P
3

I know this is a old question but lately I've been facing some similar issue while trying to decorate some React Component's methods, for debugging purposes. As people already said, arguments.caller and arguments.callee are forbidden in strict mode which is probably enabled by default in your React transpiling. You can either disable it, or I've been able to come up with another hack, because in React all class functions are named, you can actually do this:

Component.prototype.componentWillMount = function componentWillMount() {
    console.log('Callee name: ', this.__proto__.constructor.toString().substr(0,30));
...
}
Proteinase answered 18/5, 2016 at 19:8 Comment(1)
Note that Object.prototype.__proto__ is Deprecated developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Matthiew
K
3

This will work in ES5, ES6, all browsers and strict mode functions.

Here's how it looks with a named function.

(function myName() {
  console.log(new Error().stack.split(/\r\n|\r|\n/g)[1].trim());
})();
at myName (<anonymous>:2:15)

Here's how it looks with an anonymous function.

(() => {
  console.log(new Error().stack.split(/\r\n|\r|\n/g)[1].trim());
})();
at <anonymous>:2:15
Karli answered 8/5, 2019 at 12:43 Comment(3)
This produces different results per browser. Chrome: at myName (<anonymous>:2:15) Firefox: @debugger eval code:3:3Butyrate
(function myName() { console.log(new Error().stack.split(/\r\n|\r|\n/g)[1].trim().split(" ")[1]); })();Kenyon
Similar to #38435950Matthiew
G
3

A simple solution to dynamically retrieve function names [like magic variables] is the use of scoped variables.

{
  function parent() {
    console.log(a.name);
  }; let a = parent
}
{
  function child() {
    console.log(a.name)
  }; let a = child
};

parent();//logs parent
child();//logs child

Note: Nested functions cease to be source elements, and are hence not hoisted. Also, this technique cannot work with anonymous functions.

Guenon answered 24/7, 2021 at 0:46 Comment(2)
let a = go? what is go?Daytime
My bad, that's meant to be "parent"Guenon
H
2

I had a similar problem and I solved it as follows:

Function.prototype.myname = function() {
   return this.toString()
       .substr( 0, this.toString().indexOf( "(" ) )
       .replace( "function ", "" ); 
}

This code implements, in a more comfortable fashion, one response I already read here at the top of this discussion. Now I have a member function retrieving the name of any function object. Here's the full script ...

<script language="javascript" TYPE="text/javascript">

    Function.prototype.myname = function() { 
        return this.toString()
            .substr( 0, this.toString().indexOf( "(" ) )
            .replace("function ", "" ); 
    }
    function call_this( _fn ) { document.write( _fn.myname() ); }
    function _yeaaahhh() { /* do something */ }
    call_this( _yeaaahhh ); 

</script>
Harilda answered 23/8, 2014 at 20:46 Comment(0)
W
2

This worked for me.

function AbstractDomainClass() {
    this.className = function() {
        if (!this.$className) {
            var className = this.constructor.toString();
            className = className.substr('function '.length);
            className = className.substr(0, className.indexOf('('));
            this.$className = className;
        }
        return this.$className;
    }
}

Test code:

var obj = new AbstractDomainClass();
expect(obj.className()).toBe('AbstractDomainClass');
Weinert answered 8/10, 2014 at 13:23 Comment(0)
K
2

If I understood what you wanted to do, this is what I do inside a function constructor.

if (!(this instanceof arguments.callee)) {
    throw "ReferenceError: " + arguments.callee.name + " is not defined";
}
Kenyon answered 25/2, 2019 at 15:52 Comment(1)
Note: Deprecated - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Licit
P
0

Just try Function.name

const func1 = function() {};

const object = {
  func2: function() {}
};

console.log(func1.name);
// expected output: "func1"

console.log(object.func2.name);
// expected output: "func2"
Pentobarbital answered 6/9, 2022 at 10:30 Comment(1)
The question was : "How to get the function name from within that function?" In this answer function name is known and it checked from outside of function.Larios
C
-2

look here: http://www.tek-tips.com/viewthread.cfm?qid=1209619

arguments.callee.toString();

seems to be right for your needs.

Cosec answered 15/4, 2010 at 19:34 Comment(2)
arguments.callee.toString() just returns the source of the function.Courtyard
Not allowed: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to themQuail
A
-2

Easy way to get function name from within fuction you are running.

function x(){alert(this.name)};x()
Amphistylar answered 1/10, 2015 at 18:38 Comment(2)
gives me a GUIDPlectognath
be aware to the content of this it basically can be anything. try (function(){console.log(this.name);}).bind({name: "put basically anything here even an object maybe a 1TB string maybe a class definition"})()Senhauser
A
-2

you can use Error.stack to trace the function name and exact position of where you are in it.

See stacktrace.js

Almeda answered 12/9, 2016 at 0:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.