【问题标题】:How can I make a method to return an object?我怎样才能创建一个方法来返回一个对象?
【发布时间】:2023-02-25 01:19:26
【问题描述】:

我需要 getData 方法将 this.namethis.assignatures 作为对象返回。

class Student {
  constructor(name, assignatures) {
    this.name = name;
    this.assignatures = assignatures = [ "Javascript", "HTML", "CSS" ];
  }

  getData() {
    return [ this.name, this.assignatures ]
  }
}

let newStudent = new Student("Tucu")

console.log(newStudent)

let dataNewStudent = newStudent.getData();

console.log(dataNewStudent)

【问题讨论】:

  • 您是否尝试过使用object initializer
  • 使用 {} 而不是 []。 [] 是一个数组
  • 为什么不只是return this?它已经是一个对象。

标签: javascript object methods


【解决方案1】:

改变

返回 [ this.name, this.assignatures ]

返回 {name:this.name, assignatures:this.assignatures}

class Student {
  constructor(name, assignatures) {
    this.name = name;
    this.assignatures = assignatures = [ "Javascript", "HTML", "CSS" ];
  }

  getData() {
    return {name:this.name, assignatures:this.assignatures}
  }
}

let newStudent = new Student("Tucu")

console.log(newStudent)

let dataNewStudent = newStudent.getData();

console.log(dataNewStudent)

【讨论】:

  • 将您的代码设为堆栈 sn-p,以便我们可以单击“运行”按钮查看输出。
猜你喜欢
  • 2023-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-13
  • 2016-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多