如何在JavaScript中存储复杂对象

3

我有一个这样类型的复杂对象:

class Person {
  constructor(name, age, country) {
    this.name = name;
    this.age = age;
    this.country = country;
  }
  
  setName(name) {
    if (name !== null) this.name = name;
  }
  setAge(age) {
    if (age !== null) this.age = age;
  }
  setCountry(country) {
    if (country !== null) this.country = country;
  }
  
  getName() {
    return this.name;
  }
  
  // ...
}

let person = new Person('Paul', 27, 'Haïti'); // needs to save this Object
console.log(person);

我想知道有没有什么办法可以把这个对象存储起来,以便下次打开浏览器时可以访问它。localStorage不能使用。


2
存储构造函数参数(或使其序列化为此),将它们存储在本地存储中,然后从构造函数参数重新初始化。这也可以修改为构造函数(或工厂函数)接受JSON,以便对象可以序列化为JSON。 - VLAZ
当然,如果你把构造函数的参数存储在localStorage中,并调用setName或setAge等方法,则需要使用新值更新localStorage。 - Bravo
2个回答

1

本地存储是可行的 - 你只需要正确使用它

我在这个类上添加了一个 toJSON 方法 - 这将返回一个包含构造函数参数值的数组,按正确顺序排列。

class Person {
    constructor(name, age, country) {
        this.name = name;
        this.age = age;
        this.country = country;
    }
    toJSON() {
        return [this.name, this.age, this.country];
    }
    setName(name) {
        if (name !== null) this.name = name;
    }
    setAge(age) {
        if (age !== null) this.age = age;
    }
    setCountry(country) {
        if (country !== null) this.country = country;
    }
    getName() {
        return this.name;
    }
}

为了保存

const person = new Person("John", 23, "Aussie");
localStorage.setItem('test', JSON.stringify(person));

加载

const revivedPerson = new Person(...JSON.parse(localStorage.getItem('test')));

你不必编写toJSON方法,但编写会使代码更简洁(如果你从未需要将Person的实例转换为JSON字符串)。


0
我会在这个类中添加一个静态方法,它可以接受一个普通对象并返回该类的实例。你可以使用Object.createObject.assign来实现。
演示:

class Person {
  constructor(name, age, country) {
    this.name = name;
    this.age = age;
    this.country = country;
  }
  static from(obj) {
    return Object.assign(Object.create(this.prototype), obj);
  }
  getName() {
    return this.name;
  }
  // ...
}

// Demo
let person = new Person('Paul', 27, 'Haïti');
let serialised = JSON.stringify(person);
// ... write/read serialised to/from localStorage ...
// and then:
let person2 = Person.from(JSON.parse(serialised));
console.log(person2.getName());


谢谢,但我使用了一些库。我使用了tui日历,所以无法修改其中的某些内容。 - Madel M6TM
好的,但是你可以在类外部使用一个函数而不是在类上使用静态函数。如果你遇到了一个特定的类/实例问题,那么你应该在问题中真正提到它(附带示例代码)。例如,如果它是一个日期,那么只需将日期保存为字符串,在加载时设置日历对象中的适当属性即可。但这是相当具体的,与你目前的问题(Person)无关。 - trincot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接