Is it possible to get the name of the property that called the anonymous function in javascript?
var obj = {
WhoAmI: function() {
//Obtain the name WhoAmI
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With