In Node.js, I'm trying to obtain the name of current function being executed:
function doSomething[req, res] {
console.log['Function name: ' + doSomething.name];
}
This works well, but I'd like [if possible] to obtain the name within the current context. This way, if I renamed the method later I don't have change it manually. Is there a generic object [i.e. similar to 'this'] that points to the current function being executed/current context? Thank you.
asked Aug 9, 2013 at 18:14
titusmagnustitusmagnus
1,8932 gold badges21 silver badges22 bronze badges
7
Short answer: Object.values[this][0].name
or arguments.callee.name
Long Answer for the 1st option:
let myInstanceArray = Object.values[this]
Enumerates the object properties as an array
let myInstance = myInstanceArray[0]
Gets the first, and only, item in the array
let myName = myInstance.name
Gets the name of the item.
answered Dec 26, 2019 at 18:52
3
I don't want to repeat the answers in the "possible duplicate" suggestions from Ian, but there is a solution that might be worth mentioning in addition to them:
You could use a named function expression, to have one name, that is accessible from outside of the function and one name that is accessible from inside:
var x = function y[] {
console.log[y];
};
console.log[x];
Now, if you decide to give your function a different name, you can just change x
while still be able to refer to the function by using y
.
answered Aug 9, 2013 at 18:28
basilikumbasilikum
10.1k4 gold badges42 silver badges55 bronze badges
12
Not the answer you're looking for? Browse other questions tagged javascript node.js or ask your own question.
A Note: In non-standard, pre-ES2015 implementations the The function's The Function
object's read-only name
property indicates the function's name as specified when it was created, or it may be either anonymous
or ''
[an empty string] for functions created anonymously.Try it
configurable
attribute was false
as well.Description
name
property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself.name
property is read-only and cannot be changed by the assignment operator:function someFunction[] {}
someFunction.name = 'otherFunction';
console.log[someFunction.name]; // someFunction
To change it, use
Object.defineProperty[]
.
The name
property is typically inferred from how the function is defined. In the following sections, we will describe the various ways in which it can be inferred.
Function declaration
The name
property returns the name of a function declaration.
function doSomething[] {}
doSomething.name; // "doSomething"
Default-exported function declaration
An export default
declaration exports the function as a declaration instead of an expression. If the declaration is
anonymous, the name is "default"
.
// -- someModule.js --
export default function [] {};
// -- main.js --
import someModule from "./someModule.js";
someModule.name; // "default"
Function constructor
Functions created with the
Function[]
constructor have name "anonymous".
new Function[].name; // "anonymous"
Function expression
If the function expression is named, that name is used as the name
property.
const someFunction = function someFunctionName[] {};
someFunction.name; // "someFunctionName"
Anonymous function expressions created using the keyword function
or arrow functions would have ""
[an empty string] as their name.
[function [] {}].name; // ""
[[] => {}].name; // ""
However, such cases are rare — usually, in order to refer to the expression elsewhere, the function expression is attached to an identifier when it's created [such as in a variable declaration]. In such cases, the name can be inferred, as the following few subsections demonstrate.
One practical case where the name cannot be inferred is a function returned from another function:
function getFoo[] {
return [] => {};
}
getFoo[].name; // ""
Variable declaration and method
Variables and methods can infer the name of an anonymous function from its syntactic position.
const f = function [] {};
const object = {
someMethod: function [] {}
};
console.log[f.name]; // "f"
console.log[object.someMethod.name]; // "someMethod"
The same applies to assignment:
let f;
f = [] => {};
f.name; // "f"
Initializer and default value
Functions in initializers [default values] of destructuring,
default parameters, class fields, etc., will inherit the name of the bound identifier as their name
.
const [f = [] => {}] = [];
f.name; // "f"
const { someMethod: m = [] => {} } = {};
m.name; // "m"
function foo[f = [] => {}] {
console.log[f.name];
}
foo[]; // "f"
class Foo {
static someMethod = [] => {};
}
Foo.someMethod.name; // someMethod
Shorthand method
const o = {
foo[] {},
};
o.foo.name; // "foo";
Bound function
Function.prototype.bind[]
produces a function whose name is "bound " plus the function name.
function foo[] {};
foo.bind[{}].name; // "bound foo"
Getter and setter
When using get
and set
accessor properties, "get" or "set" will appear in the function name.
const o = {
get foo[] {},
set foo[x] {},
};
const descriptor = Object.getOwnPropertyDescriptor[o, "foo"];
descriptor.get.name; // "get foo"
descriptor.set.name; // "set foo";
Class
A class's name follows the same algorithm as function declarations and expressions.
class Foo {}
Foo.name; // "Foo"
Warning: JavaScript will set the function's name
property only if a function does not have an own property called name
. However, classes'
static members will be set as own properties of the class constructor function, and thus prevent the built-in name
from being applied. See an example below.
Symbol as function name
If a Symbol
is used a function name and the symbol has a description, the
method's name is the description in square brackets.
const sym1 = Symbol["foo"];
const sym2 = Symbol[];
const o = {
[sym1][] {},
[sym2][] {},
};
o[sym1].name; // "[foo]"
o[sym2].name; // "[]"
Private property
Private fields and private methods have the hash [#
] as part of their names.
class Foo {
#field = [] => {};
#method[] {}
getNames[] {
console.log[this.#field.name];
console.log[this.#method.name];
}
}
new Foo[].getNames[];
// "#field"
// "#method"
Examples
Telling the constructor name of an object
You can use obj.constructor.name
to check the "class" of an object.
function Foo[] {} // Or: class Foo {}
const fooInstance = new Foo[];
console.log[fooInstance.constructor.name]; // logs "Foo"
However, because static members will become own properties of the class, we can't obtain the class name for virtually any class with a
static method property name[]
:
class Foo {
constructor[] {}
static name[] {}
}
With a static name[]
method Foo.name
no longer holds the actual class name but a reference to the name[]
function object. Trying to obtain the class of fooInstance
via fooInstance.constructor.name
won't give us the class name at all, but instead a reference to the static class method. Example:
const fooInstance = new Foo[];
console.log[fooInstance.constructor.name]; // logs function name[]
Due to the existence of static fields, name
may not be a function either.
class Foo {
static name = 123;
}
console.log[new Foo[].constructor.name]; // 123
If a class has a static property called
name
, it will also become writable. The built-in definition in the absence of a custom static definition is read-only:
Foo.name = 'Hello';
console.log[Foo.name]; // logs "Hello" if class Foo has a static name[] property but "Foo" if not.
Therefore you may not rely on the built-in name
property to always hold a class's name.
JavaScript compressors and minifiers
Warning: Be careful when using the name
property with source-code transformations, such as those carried out by JavaScript compressors [minifiers] or obfuscators. These tools are often used as part of a JavaScript
build pipeline to reduce the size of a program prior to deploying it to production. Such transformations often change a function's name at build time.
Source code such as:
function Foo[] {};
const foo = new Foo[];
if [foo.constructor.name === 'Foo'] {
console.log["'foo' is an instance of 'Foo'"];
} else {
console.log['Oops!'];
}
may be compressed to:
function a[] {};
const b = new a[];
if [b.constructor.name === 'Foo'] {
console.log["'foo' is an instance of 'Foo'"];
} else {
console.log['Oops!'];
}
In the uncompressed version, the program runs into the truthy branch and logs "'foo' is an instance of 'Foo'" — whereas, in the compressed version it behaves differently, and runs into the else branch. If you rely on the name
property, like in the
example above, make sure your build pipeline doesn't change function names, or don't assume a function has a particular name.
Specifications
ECMAScript Language Specification # sec-function-instances-name |
Browser compatibility
BCD tables only load in the browser
See also
- A polyfill for functions'
.name
property is available incore-js
Function