How do I get the name of my variable or object?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Jeremy Wray

    How do I get the name of my variable or object?

    Hello

    On the surface this would seem quite simple, but I'm blowed if I can find a
    way to do it.

    Let's say I create a variable:

    var my_object = new Object();

    now, I want to find out the name of my object, eg. "my_object" . How do I do
    this? To make things clearer, say I want to alert out the name of my object,
    I might try something like:

    alert(my_object .name):

    this doesn't work, however. Any help appreciated...J eremy.


  • Martin Honnen

    #2
    Re: How do I get the name of my variable or object?



    Jeremy Wray wrote:[color=blue]
    > Hello
    >
    > On the surface this would seem quite simple, but I'm blowed if I can find a
    > way to do it.
    >
    > Let's say I create a variable:
    >
    > var my_object = new Object();
    >
    > now, I want to find out the name of my object, eg. "my_object" . How do I do
    > this? To make things clearer, say I want to alert out the name of my object,
    > I might try something like:
    >
    > alert(my_object .name):
    >
    > this doesn't work, however. Any help appreciated...J eremy.[/color]

    An object doesn't have a name, inside of the methods of an object you
    simply refer to
    this.property
    to access the object's properties. Other than that there is no name of
    an object and there can't be, what would you suggest the name to be with
    a code of
    var obj0, obj1;
    obj1 = obj = new Object()

    --

    Martin Honnen


    Comment

    • Douglas Crockford

      #3
      Re: How do I get the name of my variable or object?

      > Let's say I create a variable:[color=blue]
      >
      > var my_object = new Object();
      >
      > now, I want to find out the name of my object, eg. "my_object" . How do I do
      > this? To make things clearer, say I want to alert out the name of my object,
      > I might try something like:
      >
      > alert(my_object .name):[/color]

      You can create your own constructor and pass the name to it.

      function MyObject(name) {
      this.name = name;
      window[name] = this;
      }

      new MyObject('my_ob ject');

      alert(my_object .name);



      Comment

      Working...