[英]How to spread the parameters of a previous instance of a class constructor to another instance
I would like to ask what I am doing wrong here 我想问一下我在做什么错
My goal 我的目标
I want to create instances from a class constructor. 我想从类构造函数创建实例。 The first is gonna be a more generic class called Person and then another that will inherit properties from that class.
首先是一个更通用的类Person,然后是另一个将从该类继承属性的类。
My question is When all classes are set and the first instance that points to the Person constructor is declared, how could the pass the key: values
of the previous instance to the next instance since I don't want to repeat my self over the same arguments. 我的问题是,当所有类都已设置并且声明了指向Person构造函数的第一个实例时,如何将
key: values
前一个实例的key: values
传递给下一个实例,因为我不想在同一实例上重复我的自我参数。
I am currently spreading the previous parameters of the instance but obviously, I am doing something wrong. 我目前正在传播实例的先前参数,但显然,我做错了。
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());
Thank you! 谢谢!
If I understand correctly what you want to do, you need to pass only the values of the parameters that describe the Person
to the footballPlayer
(note: class names should by convention be uppercase). 如果我正确理解了您想做什么,则只需将描述
Person
的参数的值传递给footballPlayer
(注意:类名按照惯例应为大写)。
var vaggA = new footballPlayer( ...Object.values(vagg) , 'real madrid', 4);
Edit : In case you fear a different order with Object.values
(which is a real threat ), you can create a getter function in the Person
class that will return the exact list of parameters in the order they are supposed to be given to the constructor: 编辑 :如果您担心与
Object.values
不同的顺序(这是一个真正的威胁 ),则可以在Person
类中创建一个getter函数,该函数将按应将给定参数的顺序返回参数的确切列表。构造函数:
class Person {
// ...
describe() {
return [this.name, this.yearOfBirth, this.job];
}
}
const vaggA = new footballPlayer( ...vagg.describe() , 'real madrid', 4);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.