如何在类构造函数中访问JSON对象?解决类方法无法访问构造函数内JSON对象的问题
解决Test类中documents未定义的问题
我来帮你梳理下问题出在哪,以及怎么修复~
你遇到的documents未定义错误,核心原因是构造函数里用let声明的documents是局部变量,它只在构造函数的作用域内有效,类的其他方法(比如addDocument)根本访问不到它。要让类的所有方法都能共享这个对象,你需要把它挂载到类的实例上,也就是用this.documents来定义。
修正后的完整代码
const wh1 = { "key": "a", "date": "2021-07-10T08:19:44.391Z", "documents": [{"_id": "aaa"}] }; const wh2 = { "key": "b", "date": "2021-07-10T08:19:44.391Z", "documents": [{"_id": "bbb"}] }; class Test { constructor(document) { this.document = document; // 把documents挂载到实例上,替换原来的let声明 this.documents = JSON.parse('{}'); this.documents[document.date] = document; }; addDocument(doc) { // 通过this访问实例上的documents属性 this.documents[doc.date] = doc; }; print() { console.log(JSON.stringify(this.documents)); }; }; const a = new Test(wh1); a.addDocument(wh2); a.print();
关键修改点说明
- 构造函数中:将
let documents = JSON.parse('{}')改为this.documents = JSON.parse('{}'),这样documents就变成了Test实例的一个公共属性,类的所有方法都能通过this访问到它。 addDocument方法中:把documents[doc.date] = doc改为this.documents[doc.date] = doc,确保访问的是实例上的documents对象。
额外小提醒
你会发现运行修正后的代码,最终打印的结果里只有wh2的数据——因为wh1和wh2的date值完全相同,后者会覆盖前者。如果想保留同一日期下的多个文档,可以把documents的结构改成对象套数组,比如:
// 构造函数里初始化数组结构 this.documents = JSON.parse('{}'); this.documents[document.date] = [document]; // addDocument里push新文档 addDocument(doc) { if (!this.documents[doc.date]) { this.documents[doc.date] = []; } this.documents[doc.date].push(doc); };
内容的提问来源于stack exchange,提问作者Sandra Schlichting
相关产品推荐
相关产品推荐

