javascript - 如何在 javscript/node 中导入对象
问题描述
假设我有一个文件:main2.js
exports.obj = {
x : 10,
setX : function (y)
{
this.x = y;
},
getX : function()
{
return this.x;
}
};
有 2 个文件:- abc.js
const obj = require("./main2").obj;
describe("Test", function(){
it("Set X", () => {
obj.setX(50);
})
})
def.js
const obj = require("./main2").obj;
describe("Test", function(){
it("Get X", () => {
console.log(obj.getX());
})
})
当我将两个文件一起运行时,得到50 作为输出,但预期 10 作为输出,即需要两个文件都应该有不同的 obj 实例,如何实现它
解决方案
问题是您有一个对象,其中有几个对同一对象的引用。如果您希望每次都拥有不同的对象,您可能需要使用将返回该对象的函数或类。
应该是这样的:
main2.js
exports.obj = function() {
return {
x : 10,
setX : function (y) {
this.x = y;
},
getX : function() {
return this.x;
}
};
};
然后更改其他文件以使用const obj = require("./main2").obj()
推荐阅读
- python - 来自深度不均匀的嵌套字典的熊猫数据框
- r - 根据条件计算值,但以 3 行为一组
- html - HTML、CSS、链接元素的可点击范围太宽
- python - 如何访问下面的嵌套 python 列表中的各个值?循环遍历我的列表以获取它们的最佳方法是什么?
- java - 正则表达式检查 URL 语法
- disqus - Disqus API - 通过缩短的 URL 获取帖子 ID
- django - 是否有专业的方式来规划您的 REST API?
- django - 如何记录服务器的启动
- javascript - 根据按钮单击更改模态结果
- react-native - 对于通过 WebSocket 协议使用许多不同服务的 React Native 应用程序,我应该使用什么解决方案?