Function.name

Traducción en curso

The function.name property returns the name of the function.

Atributos de la propiedad Function.name
Sobrescribir No
Numerable No
Configurable
Note that in non-standard, pre-ES6 implementations the configurable attribute was false as well.

Description

The name property returns the name of a function, or (before ES6 implementations) an empty string for anonymous functions:

function doSomething() {}

console.log(doSomething.name); // logs "doSomething"

Functions created with the syntax new Function(...) or just Function(...) have their name property set to an empty string. In the following examples anonymous functions are created, so name returns an empty string:

var f = function() {};
var object = {
  someMethod: function() {}
};

console.log(f.name == ''); // true
console.log(object.someMethod.name == ''); // also true

Browsers that implement ES6 functions can infer the name of an anonymous function from its syntactic position. For example:

var f = function() {};
console.log(f.name); // "f"

You can define a function with a name in a function expression:

var object = {
  someMethod: function object_someMethod() {}
};
console.log(object.someMethod.name); // logs "object_someMethod"

try { object_someMethod } catch(e) { console.log(e); }
// ReferenceError: object_someMethod is not defined

You cannot change the name of a function, this property is read-only:

var object = {
  // anonymous
  someMethod: function() {}
};

object.someMethod.name = 'someMethod';
console.log(object.someMethod.name); // empty string, someMethod is anonymous

To change it, you could use Object.defineProperty() though.

Examples

You can use obj.constructor.name to check the "class" of an object:

function a() {}

var b = new a();

console.log(b.constructor.name); // logs "a"

Polyfill

For IE < 9, you can use fn._name() instead. For IE9+ you can use this polyfill.

Specifications

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'name' in that specification.
Standard Initial definition.
ECMAScript 2017 Draft (ECMA-262)
The definition of 'name' in that specification.
Draft  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 33.0 (Yes) No support (Yes) (Yes)
Configurable: true 43.0 38 (38) ? ? ?
Inferred names on anonymous functions 51.0 No support [1] ? ? ?
Feature Android Android Webview Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support (Yes) (Yes) (Yes) No support (Yes) (Yes) (Yes)
Configurable: true ? ? 38.0 (38) ? ? ? ?
Inferred names on anonymous functions No support 51.0 No support [1] ? ? ? 51.0

[1] See bug 883377.

Etiquetas y colaboradores del documento

 Colaboradores en esta página: jorgecasar
 Última actualización por: jorgecasar,