问题
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