【问题标题】:How to spread the parameters of a previous instance of a class constructor to another instance如何将类构造函数的前一个实例的参数传播到另一个实例
【发布时间】:2019-04-25 02:37:00
【问题描述】:

我想在这里问我做错了什么

我的目标

我想从类构造函数创建实例。 第一个是一个更通用的类,称为 Person,然后是另一个继承该类属性的类。

我的问题是 当所有类都设置好并声明了指向 Person 构造函数的第一个实例时,如何将前一个实例的 key: values 传递给下一个实例,因为我不想在相同的参数上重复我自己。

我目前正在传播实例的先前参数,但显然,我做错了什么。

class Person {
    constructor (name,yearOfBirth,job) {
        this.name = name;
        this.yearOfBirth = yearOfBirth;
        this.job = job;
    }
    getAge() {
        return new Date().getFullYear() - this.yearOfBirth
    }
    greet(){
        return `${this.name} is a ${this.getAge()} years old ${this.job}`
    }
}

class footballPlayer extends Person {
    constructor(name,yearOfBirth, job, team, cups) {
        super(name, yearOfBirth, job)
        this.team = team;
        this.cups = cups;
    }
    cupsWon() {
        console.log(`${this.name} who was bord on ${this.year} and works as a ${this.job} won ${this.cups} with ${this.team}`);
    }
}

const vagg = new Person('vaggelis', 1990, 'Developer');
const vaggA= new footballPlayer( {...vagg} , 'real madrid', 4)

console.log(vagg.greet());
console.log(vaggA.cupsWon());

谢谢!

【问题讨论】:

  • 您不能将对象传播到参数 list 中。您应该创建一个接受对象的构造函数。

标签: javascript constructor spread-syntax class-constructors


【解决方案1】:

如果我正确理解您想要做什么,您只需将描述Person 的参数值传递给footballPlayer(注意:按照惯例,类名应为大写)。

var vaggA = new footballPlayer( ...Object.values(vagg) , 'real madrid', 4);

编辑:如果您担心Object.values(即real threat)的顺序不同,您可以在Person 类中创建一个getter 函数,该函数将返回确切的列表参数的顺序应该按照它们应该提供给构造函数的顺序:

class Person {
  // ...
  describe() {
    return [this.name, this.yearOfBirth, this.job];
  }
}

const vaggA = new footballPlayer( ...vagg.describe() , 'real madrid', 4);

【讨论】:

  • Object.values does not guarantee order,所以这可能很容易中断
  • Stringin 2018 不是这样。这可以讨论,但无需对 IMO 投反对票。
  • 不幸的是,您链接的答案是错误的。请参阅我与规范中的引号链接的那个
  • 您的链接对字符串键的说明相同:“其他字符串键(如果适用),按属性创建顺序。”
  • 我已经编辑了我的答案以考虑您的陈述。感谢您让我意识到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-12
相关资源
最近更新 更多