1

I have a simple object called "obj1".

let obj1 = {
    x: 1,
    y: 5,
    meth: function() {
        return `The result of the ${this} is ${this.x+this.y}`;
    }
};

in console, it print

The result of the [object Object] is 6;

I want to get the Object name, which is obj1 but it gives me [object Object]. I tried this.name but it's showing undefined.

Pranab
  • 305
  • 3
  • 13
  • Possible duplicate of [Get name of object or class in javascript](https://stackoverflow.com/questions/10314338/get-name-of-object-or-class-in-javascript) – Splinxyy Feb 18 '18 at 14:03
  • @Splinxyy: Close, but that question (which is too broad) was asking for *either* the name of the variable or the constructor function, and the answer addresses the latter. This doesn't ask for that information. – T.J. Crowder Feb 18 '18 at 14:05
  • I actually want the variable name which is "obj1". – Pranab Feb 18 '18 at 14:13

1 Answers1

6

I want to get the Object name, which is "obj1"

No, it isn't. Objects don't have names. Your variable's name is obj1, but the object's isn't.

There is no practical way for obj1.meth to know the name of that variable (other than the programmer hardcoding it, since of course the programmer knows the name). That information just isn't provided to meth. Note that it would be context-sensitive information:

let obj1 = { /*...*/ };
let obj2 = obj1;
obj2.meth(); // Should say...what? "obj1"? "obj2"?
             // (doesn't matter, it can't say either)
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875