Search⌘ K

Name Property

Explore how the name property in ES6 functions helps retrieve function names and its role in debugging and testing. Understand why relying on constructor names is discouraged and learn how to manage object states effectively to improve code maintainability and reduce coupling.

We'll cover the following...

The name of a function can be retrieved using the name property of a function.

Node.js
let guessMyName = function fName() {};
let fName2 = function() {};
let guessMyProperty = {
prop: 1,
methodName() {},
get myProperty() {
return this.prop;
},
set myProperty( prop ) {
this.prop = prop;
}
};
console.log( guessMyName.name );
//> "fName"
console.log( fName2.name );
//> "fName2"
console.log( guessMyProperty.methodName.name );
//> "methodName"
console.log( guessMyProperty.methodName.bind( this ).name );
//> "bound methodName"

When it comes to getters and setters, retrieving method names is a bit more complicated:

Node.js
let propertyDescriptor = Object.getOwnPropertyDescriptor(
guessMyProperty, 'myProperty' );
console.log( propertyDescriptor.get.name );
//> "get myProperty"
console.log( propertyDescriptor.set.name );
//> "set myProperty"

Function names provide you with limited debugging capabilities. For instance, you can ...