Node.js 在某些情况下,require模块不会以单例模式响应对象
file_a.js是file_b.js和file_c.js的依赖项。请看一下文件_c.js,那里有一个奇怪的东西 文件a.jsNode.js 在某些情况下,require模块不会以单例模式响应对象,node.js,singleton,require,Node.js,Singleton,Require,file_a.js是file_b.js和file_c.js的依赖项。请看一下文件_c.js,那里有一个奇怪的东西 文件a.js module.exports = { test: null, setTest: function(a){ this.test = a; }, getTest: function(){ return this.test }, } 文件_b.js var a = require('./file_a')
module.exports = {
test: null,
setTest: function(a){
this.test = a;
},
getTest: function(){
return this.test
},
}
文件_b.js
var a = require('./file_a')
var b = {
print: function(someVar){
console.log(someVar);
}
}
a.setTest(b)
文件_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
throwTypeError的两个示例:无法读取null的属性“print”
file_b.js中的模块
在初始化时设置模块file_a.js中的test
属性,在您的代码片段中它永远不会初始化。要解决此问题,您需要:
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