我试图访问“技能”类,并在其他“雇员”类中使用该类来在雇员中添加技能。但我收到此错误Uncaught ReferenceError:在Employee.js:21上未定义技能,无法弄清原因

 class Skill{
    constructor(sId){
        this.sId = sId;
    }
}
if (localStorage.getItem("Skill") == null) {
    var skillList =[];
    skillList.push(new Skill("Rekruttering"));
    skillList.push(new Skill("Bogføring"));
    skillList.push(new Skill("Engros-salg"));
    skillList.push(new Skill("JavaScript"));

  if(localStorage.getItem("Skill") == null){
      skillListString = JSON.stringify(skillList);
      localStorage.setItem("Skill", skillListString);
  }
else {
    skillList = JSON.parse(localStorage.getItem("Skill"));
  }

class Employee {
    // vi bruger en constructor funktion for at lave en opskrift på objekter af en bestemt type.
    //this metoden benyttes til at referere til det tilhørende objekt
    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);
    }
}


//Employee Database "Localstorage"
if(localStorage.getItem("Employee") == null) {
    let employeeList = [];
    employeeList.push (new Employee("Simon", "Male", "HR", 1999, "[email protected]",new Skill("Sales")));
    employeeList.push (new Employee("Mads", "Male","IT", 1999,  "[email protected]"));
    employeeList.push (new Employee("Jessica", "Female", "Sales",1998, "[email protected]"));
    employeeList.push (new Employee("Benjamin", "Male","IT", 1997, "[email protected]"));

    if(localStorage.getItem("Employee") == null) {
        employeeListString = JSON.stringify(employeeList);
        localStorage.setItem("Employee", employeeListString);
        employeeList = JSON.parse(localStorage.getItem("Employee"));
    }
} else {
    employeeList = JSON.parse(localStorage.getItem("Employee"));
    document.querySelector("#employees").appendChild(buildTable(employeeList));
}

最佳答案

您需要将包含Skills类的文件导入到使用位置。

因此,您需要首先从声明了文件的文件中导出Skill类。


使用ES5:文件底部的module.exports = Skill
使用
ES6:export default Skill;


那么您将在使用技能的文件顶部导入。


使用ES5 const Skill = require('Location of file containing skill class goes here')
使用ES6 import Skill from 'location of file containing skill class'


有关更多信息:https://javascript.info/import-export

关于javascript - 尝试实例化另一个类中的类时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59265783/

10-13 01:08