首页 > 解决方案 > 将箭头函数附加到另一个箭头函数是不好的做法吗

问题描述

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功能。

这对我来说似乎很好,我只是想知道这是公认的做法,还是有什么我没有想到的。

标签: javascriptnode.jsexpress

解决方案


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));


推荐阅读