Javascript 在另一个文件上使用函数,无需 背景:
我有3个文件,Javascript 在另一个文件上使用函数,无需 背景:,javascript,node.js,node-modules,server-side,Javascript,Node.js,Node Modules,Server Side,我有3个文件,parent.js,child1.js,和child2.js let child1 = require("./child1.js") let child2 = require("./child2.js") let key = "*****" child1.start(key) child2.start(); let key = false; module.exports = { action: async()
parent.js
,child1.js
,和child2.js
let child1 = require("./child1.js")
let child2 = require("./child2.js")
let key = "*****"
child1.start(key)
child2.start();
let key = false;
module.exports = {
action: async() => {
return someApi.get(key);
},
start: async(_key) => {
key = key;
}
}
module.exports = {
action: async() => {
let res = await child1.action()
...
},
start: async() => {
// startup actions
}
}
parent.js
let child1 = require("./child1.js")
let child2 = require("./child2.js")
let key = "*****"
child1.start(key)
child2.start();
let key = false;
module.exports = {
action: async() => {
return someApi.get(key);
},
start: async(_key) => {
key = key;
}
}
module.exports = {
action: async() => {
let res = await child1.action()
...
},
start: async() => {
// startup actions
}
}
child1.js
let child1 = require("./child1.js")
let child2 = require("./child2.js")
let key = "*****"
child1.start(key)
child2.start();
let key = false;
module.exports = {
action: async() => {
return someApi.get(key);
},
start: async(_key) => {
key = key;
}
}
module.exports = {
action: async() => {
let res = await child1.action()
...
},
start: async() => {
// startup actions
}
}
child2.js
let child1 = require("./child1.js")
let child2 = require("./child2.js")
let key = "*****"
child1.start(key)
child2.start();
let key = false;
module.exports = {
action: async() => {
return someApi.get(key);
},
start: async(_key) => {
key = key;
}
}
module.exports = {
action: async() => {
let res = await child1.action()
...
},
start: async() => {
// startup actions
}
}
问题
我需要在child2
内部运行child1
中的函数,但我不能使用require
,因为只能有一个child1
有人知道这个问题的解决方案吗?谢谢我想你问错问题了:)
如果您需要child1成为独一无二的,您应该使用单音,并在任何需要的地方使用它。
//child1
let instance
module.export = () => {
if(!instance) {
instance = {
action: async() => {
return someApi.get(key);
},
start: async(_key) => {
key = key;
}
}
return instance
}
我个人不喜欢单音法,但它很方便您可以尝试的另一种方法是将child1服务实例注入child2“构造函数”
您只需导出函数而不是对象
parent.js
let child1 = require("./child1.js")()
let child2 = require("./child2.js")(child1)
let key = "*****"
child1.start(key)
child2.start();
child2
module.exports = (child1) => {
const action = async() => {
let res = await child1.action()
...
}
const start = async() => {
// startup actions
}
return {action, start}
}