首页 > 解决方案 > 我可以将 javascript 类对象存储在索引数据库中吗?

问题描述

我用构造函数和一些方法创建了一个名为 Book 的类。

class Book {
    constructor(title, author) {
        this.title = title;
        this.author = author;
    }

    displayInfo() {
        console.log(`Title: ${this.title}, Author: ${this.author}`);
    }
}

然后我创建了一堆 Book 对象,并将它们放在一个名为 Library 的数组中。

const book1 = new Book('Hobbit', 'JRR Tolkien');
const book2 = new Book('Mistborn', 'Brandon Sanderson');

let library = [];
library.push(book1);
library.push(book2);

console.log(library);
library.forEach(book => book.displayInfo());

然后我将这个库数组存储在 indexeddb 中。

if (!window.indexedDB) {
    window.alert("IndexedDB doesn't work");
}

let request = indexedDB.open("Database", 1);
let db, tx, store;
request.onupgradeneeded = function(e) {
let db = request.result;
let store = db.createObjectStore('Collection', { keyPath: 'type' });
};
request.onerror = function(e) {
    console.log('error ' + e.target.errorCode);
};
request.onsuccess = function(e) {
    db = request.result;
    tx = db.transaction('Collection', 'readwrite');
    store = tx.objectStore('Collection');

    db.onerror = function(e) {
        console.log('error ' + e.target.errorCode);
    };
    console.log('adding do collection db');
    store.put({ type: 'library', data: library });

    tx.oncomplete = function() {
        db.close();
    };
};

现在我想在每次页面刷新后恢复这个数组,并对存储在数组中的对象运行 Book 方法。但是当我恢复数据时,我发现我的 Book 对象不再是 Book 对象,只是常规对象,所以我不能对它们使用 Book 方法。

if (!window.indexedDB) {
    window.alert("IndexedDB doesn't work");
}

let request = indexedDB.open("Database", 1);
let db, tx, store;
request.onupgradeneeded = function(e) {
    console.log('upgrading');
    let db = request.result;
    let store = db.createObjectStore('Collection', { keyPath: 'type' });
};
request.onerror = function(e) { console.log('error ' + e.target.errorCode); };
request.onsuccess = function(e) {
    console.log('success');
    db = request.result;
    tx = db.transaction('Collection', 'readwrite');
    store = tx.objectStore('Collection');

    db.onerror = function(e) { console.log('error ' + e.target.errorCode); };

    let retrievedData = store.get('library');

    retrievedData.onsuccess = function(e) {
        if (retrievedData.result) console.log(retrievedData);
        if (retrievedData.result) library = retrievedData.result.data;

        console.log(library);
        library.forEach(book => book.displayInfo());
    }

    tx.oncomplete = function() {
        db.close();
    };
};

这个问题有解决方案吗?

最好的问候,奥斯卡

标签: javascriptclassindexeddb

解决方案


这不是一个好习惯,但在检索库对象后,您可以尝试:

retrievedData.onsuccess = function(e) {
    if (retrievedData.result) console.log(retrievedData);
    if (retrievedData.result) library = retrievedData.result.data;
    const fixedLibrary = library.map(book => Object.setPrototypeOf(book, Book.prototype))
    fixedLibrary.forEach(book => book.displayInfo());
}

虽然,如果您打算将实例存储在数据库中,我建议您不要使用类,而是使用面向模块的方法......


推荐阅读