Re: get object name from within object
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.javascript archive

Re: get object name from within object

From: Lasse Reichstein Nielsen <lrn@hotpop.com>
Date: Sat Jul 23 2005 - 11:07:02 CEST

"VK" <schools_ring@yahoo.com> writes:

> warteschlange wrote:
>> is there a way to find out the object/function name from inside
>> object/function.

>> function coffee(){
>> alert(this.someHowGetMyNameFuncOrVar); => should give me 'coffee'
>> }

Possible, but why bother when you can just use the string "coffee",
because the code to find the name will be inside the function with the
declared name "coffee" anyway. Ofcourse, just using a string violates
the DRY principle (Don't Repeat Yourself), but the alternatives are
not as well supported.

>>
>> var milk = new coffee(); => should give me 'milk'

Impossible.

...
> var thisName = getObjectName(arguments.callee);

Here you find the name of arguments.callee ...

> if (arguments.caller) {
> s+= "\nI'm called by ";
> s+= getObjectName(eval(thisName+".caller"));

and here you look that name up. As usual, the use of eval is
not necessary, just use the value directly:
    s+= getObjectName(arguments.callee.caller);

However, since you guard this with
   if (arguments.caller) {
you might mean to do just
    s+= getObjectName(arguments.caller);

In any case, arguments.caller and func.caller are not part of the
ECMAScript standard, and is not implemented in all browsers.

> function getObjectName(obj) {
> var tmp = obj.toString();
> return tmp.substring(tmp.indexOf(' ')+1,tmp.indexOf('('));

This can error if the obj is a function from a function expression,
see, e.g.,
 alert((function(){alert("goo");}).toString())

Still, arguments.callee is the only way to access the current function
without knowing its name. It's just that it only works inside that function,
and at that point, you should know the name.
/L

-- 
Lasse Reichstein Nielsen  -  lrn@hotpop.com
 DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
  'Faith without judgement merely degrades the spirit divine.'
Received on Tue Oct 18 03:00:17 2005