Properti function.name
mengembalikan nama fungsi.
Property attributes of Function.name |
|
---|---|
Writable | no |
Enumerable | no |
Configurable | yes |
configurable
juga false
.Deskripsi
Properti name
property mengembalikan nama sebuah fungsi , atau (sebelum implementasi ES6) string kosong untuk anonymous functions:
function doSomething() {} console.log(doSomething.name); // logs "doSomething"
Fungsi di buat menggunakan sintaks new Function(...)
atau hanya Function(...)
memiliki properti name
di set empty string. Pada contoh anonymous functions dibuat, sehingga name
mengembalikan empty string:
var f = function() {}; var object = { someMethod: function() {} }; console.log(f.name == ''); // true console.log(object.someMethod.name == ''); // also true
Browser yang mengimplementasikan fungsi ES6 mengambil nama dari anonymous function dari posisi syntactic-nya. Contoh:
var f = function() {}; console.log(f.name); // "f"
Anda bisa mendefinisikan sebuah fungsi dengan nama di 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
Anda tidak bisa mengubah nama fungsi, Properti ini hanya bisa dibaca:
var object = { // anonymous someMethod: function() {} }; object.someMethod.name = 'someMethod'; console.log(object.someMethod.name); // empty string, someMethod is anonymous
Untuk mengubah, anda perlu menggunakan Object.defineProperty()
.
Contoh
Anda bisa menggunakan obj.constructor.name
untuk memeriksa "class" dari sebuah objek:
function a() {} var b = new a(); console.log(b.constructor.name); // logs "a"
Spesifikasi
Spesifikasi | 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 |
Kompabilitas browser
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.