Javascript 寻找函数式编程模式,以防止每次初始化模块
我目前正在开发一个javascript应用程序,其组织方式如下:Javascript 寻找函数式编程模式,以防止每次初始化模块,javascript,functional-programming,ecmascript-6,Javascript,Functional Programming,Ecmascript 6,我目前正在开发一个javascript应用程序,其组织方式如下: 我有一个API模块,负责我的应用程序中的所有API调用。为了正常工作,初始化时需要几个参数,其中一个参数是hostname,其中hostname是访问服务器的域 简化版: export default = { hostname: null, initialize(hostname) { this.hostname = hostname } call(path) { const url = t
- 我有一个
模块,负责我的应用程序中的所有API调用。为了正常工作,初始化时需要几个参数,其中一个参数是API
,其中hostname
是访问服务器的域hostname
export default = {
hostname: null,
initialize(hostname) {
this.hostname = hostname
}
call(path) {
const url = this.hostname + path
return fetch(url)
}
}
// booking.js
import Api from './api'
Api.initialize('http://example.com')
export default {
getBookings () {
return Api.call('/bookings')
}
}
// users.js
import Api from './api'
Api.initialize('http://example.com')
export default {
getUsers () {
return Api.call('/users')
}
}
- 我有一个
模块(实际上还有很多模块),它使用Booking
模块向服务器发出请求。该模块定义了我们可以调用以访问服务器的函数李>API
export default = {
hostname: null,
initialize(hostname) {
this.hostname = hostname
}
call(path) {
const url = this.hostname + path
return fetch(url)
}
}
// booking.js
import Api from './api'
Api.initialize('http://example.com')
export default {
getBookings () {
return Api.call('/bookings')
}
}
// users.js
import Api from './api'
Api.initialize('http://example.com')
export default {
getUsers () {
return Api.call('/users')
}
}
我今天遇到的问题是,在使用Api
的每个“子模块”中,它都需要使用主机名反复调用初始化
我不想在Api
模块中导入hostname
,因为它可能会发生更改,而且这个库也可能被其他应用程序使用。但我希望避免在每个子模块中初始化API模块
我一直在研究函数编程、工厂函数、高阶函数等不同的模式。。。但是我找不到一个正确的方法来实现我需要做的事情
你能给我推荐一个实现这个的好方法吗
首先,您的解决方案似乎只需要从其他模块初始化一次全局服务(在本例中为Api)。OO中的单例模式已经完成了这项工作。但是,它不可测试,因为很难隔离每个子模块的测试
可测试的纯功能解决方案的一个示例是将子模块封装在以api服务为参数的高阶函数中
const bookingsApi = (api) => ({
getBookings() {
api.call(...)
}
})
export default bookingsApi
只需在api中使用全局变量并只初始化一次?OO中的单例模式有什么问题?这似乎符合您的目的。call(settings,path){const url=settings.hostname+path;…}