Reputation: 305
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
.
Upvotes: 1
Views: 122
Reputation: 1073968
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)
Upvotes: 6