javascript扩展类获取所有属性



如何从extends类中获取所有属性?

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)

有没有任何方法可以进入一个循环来获取名称、长度等,扩展类中的每个集合都是什么?

console.log(newFish[0](类似于

您的类使用extends并不是真正相关的,因为您提到的属性都是由构造的对象拥有的,而不是从原型继承的。此外,它们是可枚举的。

因此,您可以使用大多数常用的迭代方法。基本的for...in循环也能工作:

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

Object.keysObject.valuesObject.entries。。。

使用以下代码:

const myArray =  Object.values(newFish)
// you will get [ 'this is the name', '10cm' ]

最新更新