简体   繁体   English

使用构造函数获取已定义对象的名称

[英]Getting the name of a defined object with a constructor

I'm trying to get the name of an object and put it in an array after it's defined, I tried doing this code, but the name ended up being undefined any help? 我正在尝试获取对象的名称,并在定义后将其放入数组中,我尝试执行此代码,但是该名称最终undefined有帮助吗?

function command(category, help, callback) {
  this.category = category;
  this.help = help;
  this.do = callback;

  cmndlist[category].push(this.name);
}; 

Objects do not have a name or name property (unless you add one yourself). 对象没有名称或name属性(除非您自己添加一个)。 If you're referring to the variable name that references the object, that is not possible to access. 如果要引用引用该对象的变量名,则无法访问。

Let's say you create an object named "foo": 假设您创建了一个名为“ foo”的对象:

var foo = new command("category", "help", "callback");

If you want to add foo to the array cmndlist[category] , you just need to use this : 如果要将foo添加到数组cmndlist[category] ,则只需使用this

cmndlist[category].push(this.objectName);

And it will work! 它将起作用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM