简体   繁体   English

如何在另一个类中实例化一个 JavaScript 类?

[英]How to instantiate a JavaScript class in another class?

I'm currently doing a school project, the project revolves around easy access to skills in an organisation.我目前正在做一个学校项目,该项目围绕轻松获得组织中的技能展开。 I have created a class called Employee, this class have a predefined set of employees stored in localStorage (because no access to databases).我创建了一个名为 Employee 的类,这个类有一组预定义的员工存储在 localStorage 中(因为无法访问数据库)。 The list of employees is outputted via a function that creates a table of the list.员工列表是通过创建列表表的函数输出的。

Now I want to create a class called Skills, I want the Skills class be instantiated in my Employee class.现在我想创建一个名为 Skills 的类,我希望在我的 Employee 类中实例化 Skills 类。 The purpose of this is that employees should be able to enter a site and write in their skills, the skills has to be stored to a employee and the saved in localStorage and the updated in the table.这样做的目的是员工应该能够进入站点并写入他们的技能,技能必须存储到员工并保存在 localStorage 中并在表中更新。 So my problem revolves around using the right syntax / method of instantiation a class into another class..所以我的问题围绕着使用正确的语法/方法将一个类实例化为另一个类。

class Skills{
    constructor(sId){
        this.sId = sId;
    }
}
if (localStorage.getItem("Skills") == null) {
    var skillList =[];
    var skillListString = JSON.stringify(skillList);
    localStorage.setItem("skills",skillListString);
} else {
    var skillListString = JSON.parse(localStorage.getItem("Skills"));    

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 = [];

    }
}

//Employee Database "Localstorage"
if(localStorage.getItem("Employee") == null) {
    let employeeList = [];
    employeeList.push (new Employee("Simon", "Male", "HR", 1999, "2650@mail.dk"));
    employeeList.push (new Employee("Mads", "Male","IT", 1999,  "1234@email.com"));
    employeeList.push (new Employee("Jessica", "Female", "Sales",1998, "Mail2@mail.dk"));
    employeeList.push (new Employee("Benjamin", "Male","IT", 1997, "blabla@mail.dk"));

    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));
}

You instantiate a class from inside another class in the same way you always instantiate a class - with the keyword new .你从另一个类内部实例化一个类,就像你总是实例化一个类一样 - 使用关键字new

Example:例子:

class Foo {}

class Bar {
  constructor() {
    this.foo = new Foo()
  }
}

bar = new Bar()

In terms of design you may find it best to 'inject' your classes dependencies.在设计方面,您可能会发现最好“注入”您的类依赖项。 This typically leads to more testable and maintainable code.这通常会导致更可测试和可维护的代码。 clean-code-javascript has some nice examples. clean-code-javascript有一些很好的例子。

Example:例子:

class Foo {}

class Bar {
  constructor(foo) {
    this.foo = foo
  }
}

foo = new Foo()
bar = new Bar(foo)

You can definitely store instantiated classes as property:您绝对可以将实例化的类存储为属性:

// create instance in constructor
class Human {
  constructor(name, cat_name) {
    this.name = name
    this.cat = new Cat(cat_name)
  }
}

// or pass already constructed instance
class Human
  constructor(name, cat) {
    this.name = name
    this.cat = cat
  }
}

But there is less obvious problem: JSON doesn't have custom types, therefore it could only store plain JS objects, arrays, and a few primitives, like strings and numbers.但是有一个不太明显的问题:JSON 没有自定义类型,因此它只能存储普通的 JS 对象、数组和一些原语,如字符串和数字。

So custom class (and especially class stored in a property) would not survive default serialization/deserialization roundtrip.因此自定义类(尤其是存储在属性中的类)将无法在默认序列化/反序列化往返过程中幸存下来。 You cannot store references as easily as you can with plain JS objects.您无法像使用普通 JS 对象那样轻松地存储引用。 You'd have to do it yourself, for example, you could transform each class to {type:'human', fields: { name: 'John' }} object that could be safely serialized to JSON.您必须自己完成,例如,您可以将每个类转换为可以安全序列化为 JSON 的{type:'human', fields: { name: 'John' }}对象。

class Human {
  constructor(name, cat) {
    this.name = name
    this.cat = cat
  }
  serialize() {
    return { type: 'Human', fields: { cat: this.cat.serialize(), name: this.name }}
  }
}

And then deserialize according to type , invoking constructors as needed.然后根据type反序列化,根据需要调用构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM