在某些情况下,require模块不会将对象作为单例模式响应

时间:2015-10-01 00:29:47

标签: node.js singleton require

file_a.js是file_b.js和file_c.js的依赖关系。请看一下file_c.js,那里有一些奇怪的东西。

file_a.js

on result #1 used memory of 43
on result #2 used memory of 43
.....
on result #20 used memory of 43
on result #21 used memory of 49
.....
on result #32 used memory of 49
on result #33 used memory of 54
.....
on result #44 used memory of 54
on result #45 used memory of 59
.....
on result #55 used memory of 59
.....
.....
.....

on result #597 used memory of 284.3
Exceeded soft private memory limit of 256 MB with 313 MB after servicing 1 requests total

file_b.js

module.exports = {
    test: null,
    setTest: function(a){
        this.test = a;
    },
    getTest: function(){
        return this.test
    },
}

file_c.js

这种方式可行

var a = require('./file_a')
var b = {
   print: function(someVar){
       console.log(someVar);
   }
}
a.setTest(b)

这种方式不起作用

var a = require('./file_a')
console.log(typeof a.getTest().print) //function

1 个答案:

答案 0 :(得分:0)

file_c.js抛出TypeError: Cannot read property 'print' of null的两个示例。

来自file_b.js的模块在初始化时从模块test设置file_a.js属性,并且在您的代码段中它永远不会被初始化。要解决此问题,您需要:

var a = require('./file_a');
require('./file_b'); // now `test` is set
console.log(typeof a.getTest().print); // function

require('./file_b'); // module from `file_a` loaded to cache and `test` is set
var a = require('./file_a').getTest();
console.log(typeof a.print); // function