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.

3
  • Possible duplicate of Get name of object or class in javascript Commented Feb 18, 2018 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. Commented Feb 18, 2018 at 14:05
  • I actually want the variable name which is "obj1". Commented Feb 18, 2018 at 14:13

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.