0
votes

I am wondering is my class shared across instances: I have a route, for example:

/student/:id

That route activates this controller (shortened version):

module.exports = RecalculateStudents;

const recalculateActiveStudents = require('../../DataModifier/ActiveStudents');

class StudentCalculator extends AbstractStudentController {    

    startApi(request, context) {

        //Is Students shared accross the calls, or it is single instance?
        let Students = recalculateActiveStudents.recalculateStudentTimes(ctx);

        //rest of the code is here
    }
}

module.exports = RecalculateStudents;

And then I have the RecalculateStudents class (used in controller):

'use strict';

class StudentCalculator {

    constructor() {
        this.startPoint = null;
        this.finalProductStatus = null;
    }

    recalculateStudentTimes(ctx) {

        this.startGrades = ctx.currentGrades;
        this.finalStudentGrades = ctx.finalGrades;

        this.calculateActivities(this.startGrades)
    }

    calculateActivities() {        
        //
    }       
}

module.exports = new StudentCalculator();

I have removed other methods from those two classes to preserve clarity.

My question is: In the controller, I have this line of code:

let Students = recalculateActiveStudents.recalculateStudentTimes(ctx);

And inside that class I have a constructor with two variables, which I need (simple variable holders). Assume, another call is made, is the Students going to be unique, or shared between the calls?

My concern is if there are several calls (different users) that those variables will be mixed?

My understanding is that variables will not be shared, as they are exported using the keyword new.

1
Modules are shared. Variables inside functions are not, but that doesn't matter - const recalculateActiveStudents is a constant outside of your class anyway, which makes it shared amongst all instances.Bergi
Never export a new Anything. If you wanted a singleton module object, you shouldn't have used class syntax; If you wanted a class, you should export the constructor.Bergi
Yes, those properties are not shared across instances, your problem is that you are only instantiating a single one.Bergi
module.exports = new StudentCalculator(); is creating a single, global instance that is shared by your whole program. Notice that require does not re-execute modulesBergi
Yes, then each controller would get its own calculator.Bergi

1 Answers

2
votes

The variables will indeed be unique. this references whatever is using it and only that. (If I'm understanding your question right). If you did want to share the a variable in an instance across all the instances, you'd have to use its prototype. However you want to export the class and create new instances. Not export an instance of the class.