简体   繁体   中英

Why can't I iterate over the properties of a class before creating an instance?

Can someone explain to me why I can't iterate over the properties (edit: falsely wrote prototypes first) of a class without creating an instance of it? A stupid little example would be:

export class Animal {
  name: string;
  colour: string;

  constructor(init: string[]) {
    this.name = init[0];
    this.color = init[1]
  }
}

Now, somewhere else in the program (long before the first book is "created"), I would like to do this:

for (const key in  Object.keys(Animal) {
  // here I would expect to iterate over the keys 'name' and 'colour' so I can do something like:
  console.log(Animal[key]);
}

I'm aware, that it's not possible (previous post here and also according to MDN ). But I don't understand the provided explanations. Could you explain to me why this is the case?

And, as a follow-up, how would I handle such a situation? Should I create an external interface/type that I loop over? I would generally like to have a single place that "holds" my animal properties.

Because the properties of Animal are non-enumerable as can be seen in this example:

Object.getOwnPropertyDescriptors(Animal)

{
  "length": {
    "value": 1,
    "writable": false,
    "enumerable": false,
    "configurable": true
  },
  "name": {
    "value": "Animal",
    "writable": false,
    "enumerable": false,
    "configurable": true
  },
  "prototype": {
    "value": {},
    "writable": false,
    "enumerable": false,
    "configurable": false
  }
}

If you set the properties in the class to static they become enumerable. Alternatively you can iterate them this way:

for (const key in  Object.getOwnPropertyDescriptors(Animal)) {
  console.log(Animal[key]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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