This article needs an editorial review. How you can help.
This is a new technology, part of the ECMAScript 2015 (ES6) standard.
This technology's specification has been finalized, but check the compatibility table for usage and implementation status in various browsers.
La propietat function.name retorna el nom de la funció.
Property attributes of Function.name |
|
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | yes |
configurable també era false.Descripció
La propietat name retorna el nom de la funció, o una cadena buida per les funcions anònimes.
function fesAlgo() {}
console.log(desAlgo.name); // escriu "fesAlgo"
Les funcions creades amb la sintaxis new Function(...) o sols Function(...)tenen la seva propietat name en una cadena buida. En els exemples següents es creen funcions anònimes , de forma que name retorna una cadena buida:
var f = function() {};
var object = {
someMethod: function() {}
};
console.log(f.name == ''); // true
console.log(object.someMethod.name == ''); // també true
Es pot definir una funció amb un nom en un 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 no està definit
No es pot canviar el nom de la funció, aquesta propietat és només llegible:
var object = {
// anònima
someMethod: function() {}
};
object.someMethod.name = 'someMethod';
console.log(object.someMethod.name); // cadena buida, someMethod és anònima.
Per canviar-ho, es pot utilitzar Object.defineProperty().
Exemples
Es pot utilitzar obj.constructor.name per comprovar la "classe" d'un objecte:
function a() {}
var b = new a();
console.log(b.constructor.name); // escriu "a"
Especificacions
| Especificació | Estat | Comentaris |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'name' in that specification. |
Standard | Definició inicial. |
Comptabilitat amb navegadors
| Característica | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Suport bàsic | 33 | (Yes) | Not supported | (Yes) | (Yes) |
| Configurable: true | 43 | 38 (38) | ? | ? | ? |
| Característica | Android | Chrome per Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Suport bàsic | (Yes) | (Yes) | (Yes) | Not supported | (Yes) | (Yes) |
| Configurable: true | ? | ? | 38.0 (38) | ? | ? | ? |