javascript - 将箭头函数附加到另一个箭头函数是不好的做法吗
问题描述
this
假设这些函数中的任何一个都不需要。这有效
const add = (x, y) => x + y
add.foo = () => 4
console.log(add(1, 1))
console.log(add.foo())
我认为它对于打包 api 请求处理程序和函数调用非常有用,例如(假设 express.js):
const getPost = async (postId) => db.get(postId) // assuming db.get will get the post
getPost.handler = async (req, res, next) => {
try {
const { postId } = req.body
res.send(await getPost({ postId }))
} catch (err) {
next(err)
}
}
然后我可以使用app.post('/get-post', getPost.handler)
并且仍然具有很好的可测试getPost
功能。
这对我来说似乎很好,我只是想知道这是公认的做法,还是有什么我没有想到的。
解决方案
const add = (x, y) => x + y
在上面的代码中,add
是一个原型为 Function.prototype 的对象。就像 JavaScript 中的任何对象一样,它可以具有属性。这些属性本身可以是任何类型的对象。包括原型为 Function.prototype 的对象。
这不是一个坏习惯。母语实际上使用了这个。因为您的原型 Function.prototype 对象本机公开了 Function.prototype.call 或 Function.prototype.apply 等函数
例如 :
const add = (x, y) => x + y
console.log(add.call(undefined, 3, 4));
推荐阅读
- python - Countour 图 - 在 Matplotlib 中
- angular - 从 12 到 13 的角度迁移出现错误:无法解构“buildOptions.sourceMap”的属性“样式”,因为它未定义
- c# - 具有线程安全的实体框架
- linker - 如何在 XCode 9 中链接静态库
- java - 仅当从子模块触发时,Maven 构建错误
- python - 如何在列表/数组中的某个字符之后获取每个值
- keyword - BER主题;主题表征
- sql - 从 jsonb 列中生成选定行之前和之后的行
- visual-studio - 表达式抛出错误中的 SSRS 嵌套 IIF 语句
- functional-programming - 生成只有 3 个值和 2 个运算符的所有高度为 n 的树