0

Let's assume I have this class:

const Human = function () {
  this.name = 'James';
}

And I am going to create a new Person class that inherits Human:

const Person = function () {
  this.gender = 'Male';
}

Person.prototype = new Human();

Then I am going to create a new Person instance:

let _p = new Person();

How can iterate through the list of the members (name, gender)?

Ponpon32
  • 2,150
  • 2
  • 15
  • 26
  • This is not a duplicate - because when you make it in this way the properties are under __proto__ key and on the same level. @CertainPerformance – Ponpon32 Aug 03 '19 at 19:08
  • You don't need to access the object the properties are *directly* on in order to reference them, because of prototypal inheritance. `for (const prop in _p)` as described in answers in the linked question – CertainPerformance Aug 03 '19 at 19:10
  • 1
    It should be `Person.prototype = Object.create(Human.prototype)` and not an instance of the base class: [JavaScript inheritance: Object.create vs new](https://stackoverflow.com/questions/13040684) – adiga Aug 03 '19 at 19:11
  • Btw, it's *really weird* to do `Person.prototype = new Human();`. Here, the internal prototype is an *instance of another*. It would make more sense if (as almost always done) you call `Person` inside the `Human` constructor, that way `_p` would have own properties of `name` and `gender`, just like with `class` and `extends` syntax (and if you have prototype methods to inherit too, use `Object.create` like above) – CertainPerformance Aug 03 '19 at 19:11

0 Answers0