Javascript如何处理导出的模块级变量?
在Javascript应用程序中,我有一个定义为模块的服务,例如在Javascript如何处理导出的模块级变量?,javascript,Javascript,在Javascript应用程序中,我有一个定义为模块的服务,例如在services/MyService.js中 假设服务看起来是这样的: let lastUpdated; function update() { lastUpdated = new Date(); } lastUpdated = new Date(); export default { update, lastUpdated } 另一个文件,index.js,导入此服务: import MyService fr
services/MyService.js
中
假设服务看起来是这样的:
let lastUpdated;
function update() {
lastUpdated = new Date();
}
lastUpdated = new Date();
export default {
update,
lastUpdated
}
另一个文件,index.js
,导入此服务:
import MyService from "./services";
console.log(MyService.lastUpdated);
setTimeout(() => {
MyService.update();
console.log(MyService.lastUpdated);
}, 1000)
我认为调用
MyService.update()
时,MyService.lastUpdated
会改变,但事实并非如此。导入变量时,它是指向初始Date
对象的指针吗?如果是这样,我如何更新它以使“live”变量可以在其他地方访问?从这个意义上讲,变量不能实时更新。如果您使用的是ES6,那么您需要为lastUpdated
变量声明一个带有getter和setter的类:
export default class MyService {
// Member
constructor() {
this.lastUpdated = new Date();
}
// Method
update() {
this.lastUpdated = new Date();
}
}
然后,您可以使用new MyService()
创建类MyService
的新实例,然后访问lastUpdated
变量,如下所示:
import MyService from "./services";
const myService = new MyService();
// Get current timestamp
console.log(myService.lastUpdated);
window.setTimeout(() => {
// Update timestamp
myService.update();
// Get updated timestamp
console.log(myService.lastUpdated);
}, 1000);
导出默认值{update,lastUpdated}
导出属性为update
和lastUpdated
的对象。对于您正在询问的问题,对象的lastUpdated
属性没有更改,原因与以下代码中的lastUpdated
没有更改相同:
让lastUpdated;
函数更新(){
lastUpdated=新日期();
}
lastUpdated=新日期();
const MyService={
更新,
最近更新
};
log(MyService.lastUpdated);
设置超时(()=>{
MyService.update();
log(MyService.lastUpdated);
},1000)