Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/404.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript如何处理导出的模块级变量?_Javascript - Fatal编程技术网

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

在Javascript应用程序中,我有一个定义为模块的服务,例如在
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)