声明一个类 - 共享实例与否

时间:2017-07-11 07:13:39

标签: javascript node.js express

我想知道我的类是跨实例共享的: 我有一条路线,例如:

  

/学生/:ID

该路线激活此控制器(缩短版本):

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;

然后我有RecalculateStudents类(在控制器中使用):

'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();

我已从这两个类中删除了其他方法以保持清晰。

我的问题是: 在控制器中,我有这行代码:

let Students = recalculateActiveStudents.recalculateStudentTimes(ctx);

在该类中,我有一个带有两个变量的构造函数,我需要它(简单的变量持有者)。假设,另一个电话是,学生将是独特的,还是在电话之间共享?

我担心的是,是否有多个调用(不同的用户)会混合这些变量?

我的理解是不会共享变量,因为它们是使用关键字new导出的。

1 个答案:

答案 0 :(得分:2)

变量确实是唯一的。 this引用任何正在使用它的东西而且只引用它。 (如果我正确理解你的问题)。如果您确实希望在所有实例中共享实例中的变量,则必须使用其prototype。但是,您要导出类并创建新实例。 导出该类的实例。