javascript - 声明类 - 是否共享实例

标签 javascript node.js express

我想知道我的类是否在实例之间共享: 我有一条路线,例如:

/student/:id

该路由激活此 Controller (缩短版本):

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 类(在 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();

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

我的问题是: 在 Controller 中,我有这行代码:

let Students = recalculateActiveStudents.recalculateStudentTimes(ctx);

在该类中,我有一个带有两个变量的构造函数,这是我需要的(简单的变量持有者)。假设进行另一个调用,学生将是唯一的,还是在调用之间共享?

我担心的是,如果有多个调用(不同的用户)这些变量会混合在一起吗?

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

最佳答案

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

关于javascript - 声明类 - 是否共享实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45027781/

相关文章:

javascript - Node.js 文件中的单独函数

css - 如何从 React 中的实体化启用弹出菜单?

javascript - NestJS 如何使用 async/await 配置中间件?

javascript - 为什么解析时sequelize Promise 的输出不同

javascript - 协助调试这个简单的 javascript split 函数

html - 链接 metro css 和 jade

node.js - 如何在 Express js 中执行多次填充?

javascript - 基本重定向 Node js

javascript - "Cannot read property ' classList ' of null"使用classList.add时

javascript - 检查表行是否在 View 中