toJSON()
方法将Goal对象转换为JSON格式的对象。
toJSON()
返回JSON格式的对象。
const goal = new Goal("Learn JavaScript", "Strengthen coding skills",
new Date(2022, 11, 31), 10, true);
const goalJSON = goal.toJSON();
console.log(goalJSON);
输出结果:
{
"title": "Learn JavaScript",
"description": "Strengthen coding skills",
"dueDate": "2022-12-31T08:00:00.000Z",
"priority": 10,
"completed": true
}
该方法只能用于Goal对象。如果要转换其他类型的对象,请使用内置的JSON.stringify()
方法。
class Goal {
constructor(title, description, dueDate, priority, completed) {
this.title = title;
this.description = description;
this.dueDate = dueDate;
this.priority = priority;
this.completed = completed;
}
toJSON() {
return {
title: this.title,
description: this.description,
dueDate: this.dueDate.toISOString(),
priority: this.priority,
completed: this.completed
};
}
}
const goal = new Goal("Learn JavaScript", "Strengthen coding skills",
new Date(2022, 11, 31), 10, true);
const goalJSON = goal.toJSON();
console.log(goalJSON);