Getting the name of a defined object with a constructor

偶尔善良 提交于 2019-12-12 01:26:24

问题


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?

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

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

回答1:


Objects do not have a name or name property (unless you add one yourself). If you're referring to the variable name that references the object, that is not possible to access.




回答2:


Let's say you create an object named "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:

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

And it will work!



来源:https://stackoverflow.com/questions/53808062/getting-the-name-of-a-defined-object-with-a-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!