我有一个名为“obj1”的简单对象。
let obj1 = {
x: 1,
y: 5,
meth: function() {
return `The result of the ${this} is ${this.x+this.y}`;
}
};
在控制台中,打印
[object Object]的结果是6;
我希望得到Object
名称obj1
,但它会给我[object Object]
。
我尝试this.name
,但它显示undefined
。
答案 0 :(得分:6)
我想获取对象名称,即“obj1”
不,不是。对象没有名称。您的变量的名称为obj1
,但对象不是。
obj1.meth
没有实际的方法来知道该变量的名称(除了程序员对其进行硬编码,因为当然程序员知道名称)。该信息不会提供给meth
。请注意,它将是上下文相关的信息:
let obj1 = { /*...*/ };
let obj2 = obj1;
obj2.meth(); // Should say...what? "obj1"? "obj2"?
// (doesn't matter, it can't say either)