Javascript:如何在 LocalStorage 中存储 class 的实例?

Javascript: How can I store instances of a class in LocalStorage?

假设我有一个 class:

Class Comment {
    constructor(user, comment) {
        this.username = document.createElement("span");
        this.comment = document.createElement("p");
        this.body = document.querySelector("body");        
    }
    createComment() {
        this.username.textContent = user;
        this.commet.textContent = comment;

        body.appendChild(this.username);
        body.appendChild(this.comment);
    }
}

每次用户在页面上输入用户名和评论并点击提交按钮时,它都会创建 class(新评论!)的新实例:

const submitButton = document.querySelector("#submitButton");
submitButton.addEventListener("click", () => {
    let addComment = new Comment(userInput.value, commentInput.value);
}

我想将这些实例中的每一个存储在 localStorage 中(按顺序):

exisitingComments = []
localStorage.setItem("existingComments", JSON.stringify(existingComments));

存储分配给实例的变量 (addComment) 会导致方法 createComment 在加载时未定义:

window.onload = function() {
    existingComments = JSON.parse(localStorage.existingComments);
    let i = existingComments.length - 1;
    for (; i >= 0; i--) {
        existingComments[i].createCommet()
    }
}

-> TypeError: existingComments[i].createComment is not a function

我无法存储用户名和评论并创建新的 class 实例,因为用户名和评论不必是唯一的,如果用户想删除评论我无从知晓它在 localStorage 中的位置(如果可以说有多个相同的评论)。

唯一有效的是每次点击提交按钮时,调用一个函数来遍历整个评论部分:

const commentSection = document.querySelector("#commentSection").children;
for (x = 0; x < commentSection.length - 1; x++) {
    commentSection[x].setAttribute("id", `comment#{x}`);
}

这些id对应的是评论在localStorage中的位置。

有谁知道可以实现此目的的更好方法吗?提前一百万致谢!!

这里的核心问题是本地存储仅存储字符串 (documentation),而您使用的是 JSON 编码。 JSON 不支持 classes 或 DOM 元素。您需要引入某种序列化来表示您的 class 并稍后再水化它。

有关 Javascript 中序列化的更多指导,请参阅 this question

DOM 问题在那个问题中没有评论,但是如果你的反序列化机制创建了你的 Comment class 的新实例,它应该有创建新 DOM个元素。