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

require module does not respond object as singleton pattern in some cases

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

file_a.js

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

file_b.js

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

file_c.js

这种方式行得通

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

这种方式行不通

var a = require('./file_a').getTest() 
console.log(typeof a.print)  //Cannot read property 'print' of null

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

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

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