【发布时间】: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