【问题标题】:javascript extends class get all the properties [duplicate]javascript扩展类获取所有属性[重复]
【发布时间】:2021-01-09 01:58:49
【问题描述】:

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

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]) 类似的东西

【问题讨论】:

    标签: javascript node.js class extends super


    【解决方案1】:

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

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

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

    或者Object.keys, Object.values, Object.entries, ...

    【讨论】:

      【解决方案2】:

      使用下面的代码:

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

      【讨论】:

        猜你喜欢
        • 2013-04-05
        • 1970-01-01
        • 1970-01-01
        • 2015-09-30
        • 1970-01-01
        • 2020-12-11
        • 1970-01-01
        • 2017-09-19
        • 1970-01-01
        相关资源
        最近更新 更多