【问题标题】:How to access JSON object in constructor?如何在构造函数中访问 JSON 对象?
【发布时间】:2021-07-19 13:25:00
【问题描述】:

在下面我试图创建一个Test 类,其中构造函数初始化一个名为documents 的JSON 对象和一个方法addDocument(),它将一个JSON 字符串添加到documents JSON 对象。

我得到的错误是documents is not defined in

documents[doc.date] = doc;

我不明白如何通过addDocuemnts() 方法访问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;

    let documents = JSON.parse('{}');
    documents[document.date] = document;
  };

  addDocument(doc) {
    documents[doc.date] = doc;
  };

  print() {
    console.log(JSON.stringify(this.documents));
  };
};

const a = new Test(wh1);
a.addDocument(wh2);
a.print();

【问题讨论】:

    标签: javascript node.js ecmascript-6


    【解决方案1】:

    您从未在对象本身上设置this.documents

    您当前正在构造函数中创建一个局部变量 let 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;
    
        this.documents = JSON.parse('{}');
        this.documents[document.date] = document;
      };
    
      addDocument(doc) {
        this.documents[doc.date] = doc;
      };
    
      print() {
        console.log(JSON.stringify(this.documents));
      };
    };
    
    const a = new Test(wh1);
    a.addDocument(wh2);
    a.print();

    【讨论】:

      猜你喜欢
      • 2018-06-24
      • 2018-08-30
      • 1970-01-01
      • 2021-09-04
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多