Skip to content

Instantly share code, notes, and snippets.

@gologo13
Last active January 23, 2022 06:05
Show Gist options
  • Save gologo13/ba238af013c9132232ee to your computer and use it in GitHub Desktop.
Save gologo13/ba238af013c9132232ee to your computer and use it in GitHub Desktop.
Circular dependency problem and its solutions for node.js
"use strict";
var B = require('./b');
var A = module.exports = (function() {
var id, bInstance;
return {
init: function init(val) {
id = val;
bInstance = new B();
return this;
},
doStuff: function doStuff() {
bInstance.stuff();
return this;
},
getId: function getId() {
return id;
}
};
}());
// solution 3: dependency injection
"use strict";
var B = require('./b');
var A = module.exports = (function() {
var id, bInstance;
return {
init: function init(val) {
id = val;
bInstance = new B(this); // 注目!
return this;
},
doStuff: function doStuff() {
bInstance.stuff();
return this;
},
getId: function getId() {
return id;
}
};
}());
[Hoover:
// solution 2: lazy require
"use strict";
var A = module.exports = (function() {
var id, bInstance;
return {
init: function init(val) {
id = val;
bInstance = (new require('./b'))(); // 注目!
return this;
},
doStuff: function doStuff() {
bInstance.stuff();
return this;
},
getId: function getId() {
return id;
}
};
}());
// solution 1: module.exports first
"use strict";
var A = module.exports = {}; // 注目!
var B = require('./b');
var id, bInstance;
A.init = function init(val) {
id = val;
bInstance = new B();
return this;
};
A.doStuff = function doStuff() {
bInstance.stuff();
return this;
};
A.getId = function getId() {
return id;
};
"use strict";
var A = require('./a');
var B = module.exports = function() {
return {
stuff: function stuff() {
console.log('I got the id: ', A.getId());
}
};
};
"use strict";
var B = module.exports = function(A) {
var DI = A;
return {
stuff: function stuff() {
console.log('I got the id: ', DI.getId()); // 注目!
}
};
};
"use strict";
var A = require('./a')
A.init(1234).doStuff();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment