0

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);
}; 
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Kikasuru
  • 11
  • 2
  • What do you mean with "Name of an object" is there a `name`attribute in that object? – rubentd Dec 17 '18 at 01:44
  • Which object are you trying to get the name of? – theonlygusti Dec 17 '18 at 01:44
  • Let's say, for example I define a object named "foo", I'm trying to get it to add "foo" to the array. – Kikasuru Dec 17 '18 at 01:46
  • Wanting to do this is usually a sign that you're thinking about things incorrectly. The variable that points to an object isn't the name of the object (more than one variable can point to the same object). You would typically push the object itself into the array — it doesn't push a copy of the object, but a reference to the object). Maybe if you explain why you need this someone will offer a better way forward. – Mark Dec 17 '18 at 02:39

2 Answers2

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.

rich
  • 91
  • 2
  • In the world of minified code, it's probably for the best. If your code relied on certain variable names, minifying would most likely cause bugs in your code. – rich Dec 17 '18 at 02:45
0

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!

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • Well I don't want the whole function in an array, I just want the name of it. – Kikasuru Dec 17 '18 at 02:02
  • Where did the `this.objectName` property come from? – Mark Dec 17 '18 at 02:06
  • @MarkMeyer It came from the second line of code in this question https://stackoverflow.com/questions/10314338/get-name-of-object-or-class Look at the comment after the `window.alert` statement, and the actual statement as well. – Jack Bashford Dec 17 '18 at 02:18
  • @JackBashford that questions is asking how to get the name of the object, which suggests the code in their example doesn't work (and it doesn't). Unless you put an `objectName` property on the object, it's undefined. – Mark Dec 17 '18 at 02:33