如何编写返回对象的方法?需改造Student类的getData方法返回指定对象
修改Student类的getData方法返回对象
要让getData方法返回包含name和assignatures的对象,只需把原本返回数组的代码改成返回对象字面量即可,同时可以利用ES6属性简写让代码更简洁。
修改后的完整代码
class Student { constructor(name, assignatures) { this.name = name; // 修正构造函数赋值逻辑:传入assignatures则用传入值,否则用默认数组 this.assignatures = assignatures ?? [ "Javascript", "HTML", "CSS" ]; } getData() { // 返回包含指定属性的对象 return { name: this.name, assignatures: this.assignatures }; // 更简洁的ES6写法: // const { name, assignatures } = this; // return { name, assignatures }; } } let newStudent = new Student("Tucu") console.log(newStudent) let dataNewStudent = newStudent.getData(); console.log(dataNewStudent)
关键修改说明
- 原
getData返回数组[this.name, this.assignatures],现在改为返回对象结构,调用getData()后会直接得到包含name和assignatures属性的对象。 - 顺带修正了构造函数的赋值问题:原代码
this.assignatures = assignatures = [ ... ]会强制覆盖传入的assignatures参数,改用??空值合并运算符后,只有当参数为null/undefined时才使用默认数组,保留了传入参数的有效性。
执行结果
修改后执行代码,console.log(dataNewStudent)会输出:
{ name: 'Tucu', assignatures: [ 'Javascript', 'HTML', 'CSS' ] }
内容的提问来源于stack exchange,提问作者Tucu
相关产品推荐
相关产品推荐

