Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain property name within anonymous function in Javascript

Is it possible to get the name of the property that called the anonymous function in javascript?

Example

var obj = {
     WhoAmI: function() {
       //Obtain the name WhoAmI
     }
}
like image 470
Jonathan Sheely Avatar asked Apr 14 '26 19:04

Jonathan Sheely


1 Answers

The function has no (direct) idea what the name of the property or variable is that references it.

Though depending on the means of invocation, it could be discovered.

var obj = {
     WhoAmI: function func() {
         for (var p in this)
             if (this[p] === func)
                 alert(p);
     }
}

obj.WhoAmI();

DEMO: http://jsfiddle.net/wUdNf/

This only works if the function is invoked with its this set as the object referencing it.

You could use arguments.callee instead of giving the function a name, though that's not permitted in strict mode.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!