我很难弄清楚如何将我的类保存到localStorage
中,例如,当我找回它时,仍然可以调用我定义的实例方法。
以下是引发错误的示例:
class Employee {
constructor(name, gender, department, yy, email) {
this.name = name;
this.gender = gender;
this.department = department;
this.email = email;
this.skills = [];
}
addNewSkill(skill){
this.skills.push(skill);
}
}
const employee = new Employee({
name: "John Doe",
gender: "male",
department: "CS",
email: "john@doe.com"
});
employee.addNewSkill("coding");
localStorage.setItem("employees", employee);
const retrievedEmployee = JSON.parse(localStorage.getItem("employee"));
// Throws Uncaught TypeError: retrievedEmployees[0].addNewSkill is not a
// function.
retrievedEmployee.addNewSkill("reading");
答案 0 :(得分:2)
JSON.stringify
将对象变成字符串时,对象丢失其类型。尽管保留了它们的属性和值,但有关其为Employee
实例这一事实的所有信息都会丢失。
从window.localStorage
检索后,当JSON.parse
保存的字符串时,您将创建普通对象而不是实际的Employee
对象,因此,检索到的对象缺少employee.addNewSkill()
方法。
您应确保您的Employee
类允许使用类似Employee
的对象轻松实例化,然后每次从LocalStorage检索保存的Employee时,都实例化 new {{ 1}}来自该对象的实例,如下所示:
这是一个例子:
Employee
为了记录,我以前在一个大型项目中遇到过这个问题,并使用了一个名为typeson的npm模块,该模块允许序列化和反序列化自定义类型。
答案 1 :(得分:0)
正如Nik Kyriakides在评论中所说,您可以这样做。可以这样使用:
const Employee = require('./path/to/Employee.js');
const employee = new Employee('Jane Doe', 'Female', 'Development', 'jdoe@acme.com', [ 'html', 'css' ]);
employee.addNewSkill('javascript');
console.log(employee.skills);
或者,您可以使用setter:
...
set skills (skill) {
this.skills.push(skill);
}
...
然后将其用作:
const Employee = require('./path/to/Employee.js');
const employee = new Employee('Jane Doe', 'Female', 'Development', 'jdoe@acme.com', [ 'html', 'css' ]);
employee.skills = 'javascript';
console.log(employee.skills);
但是从句法上讲,这似乎应该是在设置而不是在数组上附加数组,因此对于这种情况,它可能不是一个好选择。我的确想在这里提及它,以便为您提供一些有关如何获取和设置其他类变量的想法。
在您的示例中,我将通过以下方式进行设置:
Employee.js
module.exports = class Employee {
constructor(name, gender, department, yy, email, skills) {
this.name = name;
this.gender = gender;
this.department = department;
this.email = email;
this.skills = [];
}
addNewSkill(skill){
this.skills.push(skill);
}
}
然后使用您的员工列表,我会做这样的事情,可能需要进行一些调整,但是只是为了给您一个想法:
index.js
const Employee = require('./path/to/Employee.js');
const fs = require('fs');
const employees = fs.readFileSync('employees.txt').toString().split("\n");
let employeeList = [];
employees.forEach(employeeData => {
const employee = JSON.parse(employeeData);
const { name, gender, department, email, skills } = employee;
employeeList.push(new Employee(name, gender, department, email, skills));
})
//do stuff with employeeList