就像这个主题。我有一个类似下面的函数,并且我在函数中声明了很多帮助函数(比示例中的函数多两倍),因为它是唯一使用它们的函数。
我的问题是:我应该在函数外部提取那些帮助函数以维持规则“函数应该做好一项工作并做好”还是应该在其中?我还读到更高级别的功能应该更高,以便于更好的可读性,但是它某种程度上是行不通的(不应该通过吊装使其起作用吗?)。
const queryThings = async (body = defaultBody) => {
try {
(...)
// helping functions
const isNonTestDeal = obj => (...)
const isNonEmpty = obj => (...)
const replaceHTMLEntity = obj => (...)
const extractCountries = o => (...)
const queried = await query(...) // that one is outside this function
const cases = queriedCases
.filter(isNonTestDeal)
.map(obj => {
let countries = [(...)]
.filter(isNonEmpty)
.map(replaceHTMLEntity)
.map(extractCountries)
let data = {
(...)
}
return data
})
.filter(obj => (...))
.sort((a,b) => a.d - b.d)
.slice(0, 45) // node has problem with sending data of more than 8KB
return cases
} catch (error) {
console.log(error)
}
}
答案 0 :(得分:3)
如果在外部声明该函数,并且仅在一个函数中使用它,则会导致名称空间污染。 (What is namespace pollution?)因此,我建议将其保留在内部。另外,如果您这样做的话,也更容易阅读,因为它更接近使用它的代码。
要解决有关提升的问题,只有在声明函数而不将其分配给变量的情况下,该函数才起作用。
答案 1 :(得分:0)
我认为当您在其他函数中编写函数时,内存使用要比写出函数更好 但是您不能在其他函数中使用它是局部函数,而不是公共函数