简体   繁体   English

如何从父 class 解析的数据中访问属性?

[英]How to access the properties from data being parsed by a parent class?

I created a base class that parses a json file:我创建了一个解析 json 文件的基本 class :

const fs = require("fs");

class DataRepository {
  constructor() {
    this.filename = "cales_data.json";
    try {
      fs.accessSync(this.filename);
    } catch (error) {
      console.error("data does not exist");
    }
  }

  async getAll() {
    // Open the file called this.filename
    return JSON.parse(
      await fs.promises.readFile(this.filename, {
        encoding: "utf-8",
      })
    );
  }

  async getOneBy(filters) {
    const records = await this.getAll();

    for (let record of records) {
      let found = true;

      for (let key in filters) {
        if (record[key] !== filters[key]) {
          found = false;
        }
      }

      if (found) {
        return record;
      }
    }
  }
}

module.exports = DataRepository;

I don't care for its methods at this point.在这一点上,我不在乎它的方法。 I just want to be able to access the contents of this.filename = "cales_data.json";我只想能够访问this.filename = "cales_data.json";的内容

Something like this perhaps:可能是这样的:

const DataRepository = require("./repositories/data");

class Address extends DataRepository {
  constructor() {
    super();
    this.Address = DataRepository.Address;
    this.Latitude = DataRepository.Latitude;
    this.Longitude = DataRepository.Longitude;
  }
}

module.exports = Address;

but obviously the above gives me undefined.但显然以上给了我未定义的。 Is it possible to access those properties inside that JSON file in that base class this way?是否可以通过这种方式访问基础 class 中的 JSON 文件中的这些属性? If so, how?如果是这样,怎么做?

Simple answer: no.简单的回答:没有。 "This" can never result to anything than a value on the class memory stack.除了 class memory 堆栈上的值之外,“这个”永远不会产生任何结果。 You have to handle this different:-)你必须处理这个不同的:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM