首页 > 解决方案 > 如何在 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 实例,如何实现它

标签: javascriptnode.jsmocha.js

解决方案


问题是您有一个对象,其中有几个对同一对象的引用。如果您希望每次都拥有不同的对象,您可能需要使用将返回该对象的函数或类。

应该是这样的:

main2.js

exports.obj = function() {
  return {
    x : 10,
    setX : function (y) {
      this.x = y;
    },
    getX : function() {
      return this.x;
    }
  };
};

然后更改其他文件以使用const obj = require("./main2").obj()


推荐阅读