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.
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.
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 thefootballPlayer
(note: class names should by convention be uppercase).Edit: In case you fear a different order with
Object.values
(which is a real threat), you can create a getter function in thePerson
class that will return the exact list of parameters in the order they are supposed to be given to the constructor: