0

How can I get all the properties from extends class?

class Fish {
  constructor(name) {
    this.name ="this is the name"
  }
}

class Trout extends Fish {
  constructor(name, length) {
    super(name)
    this.length = "10cm"
  }
}

let newFish =new Trout()
console.log (newFish.name)
console.log (newFish.length)

Is there any way to get in a loop to get name,length,etc what every set it in the extends classes?

console.log(newFish[0]) something like that

Kenot Solutions
  • 377
  • 1
  • 4
  • 11

2 Answers2

1

That your class uses extends is not really relevant, as the properties you mention are both owned by the constructed object, and not inherited from a prototype . Also, they are enumerable.

So you can use most of the usual iteration methods. The basic for...in loop will work too:

for (let prop in newFish) {
    console.log (prop, ":", newFish[prop])
}

Or Object.keys, Object.values, Object.entries, ...

trincot
  • 317,000
  • 35
  • 244
  • 286
-1

use the code below:

const myArray =  Object.values(newFish)
// you will get [ 'this is the name', '10cm' ]
Besufkad Menji
  • 1,433
  • 9
  • 13