1

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). 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. 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. 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, "[email protected]"));
    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));
}
9
  • mention your previous programming language may help. I mean, your question doesn't sound like a problem at all in javascript world. Commented Dec 9, 2019 at 16:17
  • 1
    Same as instantiating it anywhere else, new SomeClass(). Commented Dec 9, 2019 at 16:17
  • You've shown that you know how to instantiate the Employee class in your code. Do the same with Skills. Commented Dec 9, 2019 at 16:19
  • @appleapple there is a JS tag ;) Commented Dec 9, 2019 at 16:19
  • @HereticMonkey my problem is that I can't figure out how I use my Skills class within my Employee Class Commented Dec 9, 2019 at 16:20

2 Answers 2

5

You instantiate a class from inside another class in the same way you always instantiate a class - with the keyword 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.

Example:

class Foo {}

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

foo = new Foo()
bar = new Bar(foo)
Sign up to request clarification or add additional context in comments.

11 Comments

I believe it should pass instance not type. (btw, I personally don't like DI)
@appleapple I believe I am passing an instance. The usefulness of DI will depend on the problem but it's still an important pattern to be aware of.
oh, my mistake.
@appleapple could you please elaborate as to why You don’t like DI. I thought that made for loose coupling ? Would appreciate your input!
@KevinGreetham I'm not really sure what I think that time. But (use this answer for example) basically if you create Foo only to feed Bar, better to let Bar decide which it want (as implementation detail). It's not like you can create arbitrary Foo that'd make Bar work, and most of the time there is only 1 reasonable Foo that fits.
|
3

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.

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. 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.

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.

1 Comment

After trying different ways, instantiating the class inside the constructor was a good hint in my case. Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.