Function.name

  • Revision slug: JavaScript/Reference/Global_Objects/Function/name
  • Revision title: name
  • Revision id: 1045
  • Created:
  • Creator: Seant23
  • Is current revision? No
  • Comment

Revision Content

Summary

The name of the function.

Property of Function

Read-only

Implemented in: ? (at least since JavaScript 1.3)
ECMA Version: none

Description

The name property returns the name of a function, or an empty string for anonymous functions:

function doSomething() {}
alert(doSomething.name); // alerts "doSomething"

Note that in these examples anonymous functions are created, so name returns an empty string:

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

alert(f.name == ""); // true
alert(object.someMethod.name == ""); // also true

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

var object = {
  someMethod: function object_someMethod() {}
};
alert(object.someMethod.name); // alerts "object_someMethod"

try { object_someMethod } catch(e) { alert(e); }
// ReferenceError: object_someMethod is not defined

Examples

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

function a()
{
}

var b = new a();
alert(b.name); //Alerts "a"

Revision Source

<p>
</p>
<h3 name="Summary"> Summary </h3>
<p>The name of the function.
</p>
<table class="fullwidth-table">
<tbody><tr>
<td class="header" colspan="2">Property of <a href="en/Core_JavaScript_1.5_Reference/Global_Objects/Function">Function</a></td>
</tr>
<tr><td colspan="2">
<p><b>Read-only</b>
</p>
</td>
</tr><tr>
<td>Implemented in:</td>
<td>? (at least since JavaScript 1.3)</td>
</tr>
<tr>
<td>ECMA Version:</td>
<td>none</td>
</tr>
</tbody></table>
<h3 name="Description"> Description </h3>
<p>The name property returns the name of a function, or an empty string for anonymous functions:
</p>
<pre class="eval">function doSomething() {}
alert(doSomething.name); // alerts "doSomething"
</pre>
<p>Note that in these examples anonymous functions are created, so <code>name</code> returns an empty string:
</p>
<pre class="eval">var f = function() { };
var object = {
  someMethod: function() {}
};

alert(f.name == ""); // true
alert(object.someMethod.name == ""); // also true
</pre>
<p>You can define a function with a name in a function expression:
</p>
<pre class="eval">var object = {
  someMethod: function object_someMethod() {}
};
alert(object.someMethod.name); // alerts "object_someMethod"

try { object_someMethod } catch(e) { alert(e); }
// ReferenceError: object_someMethod is not defined
</pre>
<h3 name="Examples"> Examples </h3>
<p>You can use <code>obj.constructor.name</code> to check the "class" of an object:
</p>
<pre class="eval">function a()
{
}

var b = new a();
alert(b.name); //Alerts "a"
</pre>
Revert to this revision