我很困惑。
有时,当我的 Web api 接收数据时,它会混合对象之间的数据,在我看来,文件中的全局对象实际上是持久的。
这是代码的基本布局
处理程序.js
const something = require('./otherfile')
let handlers ={}
handlers.customers = function (data, callback) {
let acceptableMethods = ['post'];
if (acceptableMethods.indexOf(data.method) > -1) {
handlers._customers[data.method](data, callback);
} else {
callback(405);
}
};
handlers._customers = {}
handlers._customers.post = async function (data, callback) {
customer.new(data);
callback(200, 'success')
}
其他文件.js
let contacts_list = [];
let accountData = {};
module.exports = something = {
new: {
dostuff: async function (data) {
// update and reference global objects here..
accountData.name = data.name;
accountData.otherProperty = await somefunction(data.prop)
}
}
}
我预计,由于它需要导出的模块,因此每次调用导出的模块时,它都会被视为自己的对象,但是,似乎该对象没有被视为唯一的,而是被覆盖部分和“随机”。这对我来说意味着我可以导出一个变异对象,例如跨文件的数组
我认为全局在多个请求中被持久化是正确的吗? 在导出对象中设置全局是否会以任何方式影响该对象的行为?在这种情况下,我不希望这些数据发生变异。
预先感谢您的建设性批评和指导:)
最佳答案
[重构您的代码,以便您在每个请求上创建一个新对象。模块在第一个请求时缓存,因此所有变量和对象属性都将在调用期间保留。
//处理程序.js
const somethingFactory = require('./otherfile')
module.exports = function(){
let handlers = {}
const something = somethingFactory();
handlers.customers = function (data, callback) {
let acceptableMethods = ['post'];
if (acceptableMethods.indexOf(data.method) > -1) {
handlers._customers[data.method](data, callback);
} else {
callback(405);
}
};
handlers._customers = {}
handlers._customers.post = async function (data, callback) {
customer.new(data);
callback(200, 'success')
}
return handlers;
};
其他文件.js
module.exports = function(){
let contacts_list = [];
let accountData = {};
return {
new: {
dostuff: async function (data) {
// update and reference global objects here..
accountData.name = data.name;
accountData.otherProperty = await somefunction(data.prop)
}
}
}
};
关于javascript - module.export 和全局对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54203094/