我有一个工厂函数如下:
import moduleA from'./modulea'
import moduleB from'./moduleb'
import { componentA, componentB } from './components'
module.exports = () => {
//DECLARE VARIABLES SHARED BY FUNCTIONS
const util = moduleA.util() //RETURNS OBJECT
return Object.assign({}, {
componentA,
componentB
}
}
最初,componentA 和 componentB 是工厂函数中的函数,声明变量部分中的任何导入模块或变量在每个组件中都可用。
import moduleA from'./modulea'
import moduleB from'./moduleb'
module.exports = () => {
//DECLARE VARIABLES SHARED BY FUNCTIONS
const util = moduleA.util() //RETURNS OBJECT
const componentA = () => {
//MODULES AVAILABLE
//DECLARED VARIABLES AVAILABLE
//DO STUFF
}
const componentA = () => {
//MODULES AVAILABLE
//DECLARED VARIABLES AVAILABLE
//DO STUFF
}
return Object.assign({}, {
componentA,
componentB
}
}
自从将函数移动到 './components'
后,作为每个函数的单独文件,导入的模块和声明的变量现在对组件不再可用,即使使用 Object.assign 也是如此。我试过将它们传递给 Object.assign 无济于事。
有没有办法让导入的模块和声明的变量可用于我导入的组件,这样我就可以将工厂分解成单独文件中的较小组件,而不必在每个组件文件中导入它们?我正在尝试通过关闭来做到这一点。
最佳答案
您的组件模块还应该导入它需要的任何模块。
// "components" module
// Just like any other module, import what you need
import moduleA from'./modulea'
import moduleB from'./moduleb'
const util = moduleA.util()
export const componentA = () => {
//MODULES AVAILABLE
//DECLARED VARIABLES AVAILABLE
//DO STUFF
}
export const componentA = () => {
//MODULES AVAILABLE
//DECLARED VARIABLES AVAILABLE
//DO STUFF
}
编辑(回应评论):
我不一定推荐这些其他选项中的任何一个,但这里有一些您可以做的其他事情:
1) 将所有内容附加到“this”。
// "components" module
// Component functions are non-arrow functions so you can use "this"
export function componentA() {
this.moduleA
this.moduleB
this.util
}
export function componentA() {
this.moduleA
this.moduleB
this.util
}
然后在你的主模块中:
module.exports = () => {
//DECLARE VARIABLES SHARED BY FUNCTIONS
const util = moduleA.util() //RETURNS OBJECT
return Object.assign({}, {
componentA,
componentB,
// other properties the component functions expect to have
moduleA,
moduleB,
util
}
}
或者 2) 将所有内容作为参数传递:
// "components" module
export const componentA = (moduleA, moduleB, util) => {
//MODULES AVAILABLE
//DECLARED VARIABLES AVAILABLE
//DO STUFF
}
export const componentA = (moduleA, moduleB, util) => {
//MODULES AVAILABLE
//DECLARED VARIABLES AVAILABLE
//DO STUFF
}
然后在你的主模块中:
module.exports = () => {
//DECLARE VARIABLES SHARED BY FUNCTIONS
const util = moduleA.util() //RETURNS OBJECT
return Object.assign({}, {
componentA: (...args) => componentA(moduleA, moduleB, util, ...args),
componentB: (...args) => componentB(moduleA, moduleB, util, ...args),
}
}
附言
each function in components has it's own file ... the functions that are now methods on that new object
您在单独的文件中定义方法很奇怪。您可能在这里遇到更深层次的设计问题。
关于javascript - 使用 Object.assign(闭包)在工厂内使用导入的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46961153/