实现说明
除了类 Money,文件里再无其他定义。
顶层就这几处状态:invoice、restored。
常见问题
运行前要先安装什么?
什么都不用额外装——运行时自带了代码所需的一切。 跨调用保留的状态放在这些顶层绑定里:invoice、restored。
核心语句
return (this.cents / 100).toFixed(2) + ' ' + this.currency;
const restored = JSON.parse(JSON.stringify(invoice));
代码示例
// toJSON 决定自定义类型在 JSON.stringify 里写出的形状
class Money {
constructor(cents, currency = 'USD') {
this.cents = cents;
this.currency = currency;
}
toJSON() {
return (this.cents / 100).toFixed(2) + ' ' + this.currency;
}
}
const invoice = { total: new Money(12345), due: new Date('2026-03-01T00:00:00Z') };
console.log('Money.toJSON :', invoice.total.toJSON());
console.log('Date.toJSON :', invoice.due.toJSON());
// stringify 对每个值调用 toJSON,而不是展开自有字段
console.log('stringified :', JSON.stringify(invoice));
// 解析回来只是普通对象:toJSON 是单向的序列化契约
const restored = JSON.parse(JSON.stringify(invoice));
console.log('parsed back :', typeof restored.total, JSON.stringify(restored));