gpt4 book ai didi

javascript - 在js文件之间共享对象的最佳方式

转载 作者:行者123 更新时间:2023-12-02 21:47:24 24 4
gpt4 key购买 nike

我想在多个文件之间共享此对象,以便它们能够读取和修改它。

obj = {id: 34234, name: 'xxxx', surname: 'yyyy'};

我应该像这样将我的 js 文件导入到我的所有 html 文件中

html1.html <script src='myObj.js'></script>
html2.html <script src='myObj.js'></script>
html3.html <script src='myObj.js'></script>
...

或者使用localstorage.setItem()/localstorage.getItem()?哪种方法最好?

观察: 如果您对上下文感兴趣,它是关于调用返回 users/projetcs/project-steps 的 API...当用户登录时,我想获取他们所有的项目。如果用户编辑它,则通过其 id 加载项目 obj 并更改它,然后将更改发送到服务器。同样的情况也发生在项目步骤等其他事情上(但这被加载到另一个页面中)。

最佳答案

您必须在任何其他文件之前调用此文件,如果您使用ajax,请务必在ajax请求的SUCCESS CALLBACK中调用其他函数

var commonModule = (function() {
'use strict';

var userInfo = { id: 1, name: 'go' }; // use ajax to set it if you want

return {
userInfo: userInfo
};
})();

//in another file you can call

console.log(commonModule.userInfo.name);

关于javascript - 在js文件之间共享对象的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60219778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com