假设在任何这些函数中都不需要 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
是一个原型(prototype)为Function.prototype的对象。就像 JavaScript 中的任何对象一样,它可以具有属性。这些属性本身可以是任何类型的对象。包括原型(prototype)为 Function.prototype 的对象。
这不是一个坏习惯。母语实际上使用这个。因为你的原型(prototype) Function.prototype 的对象本身暴露了像 Function.prototype.call 或 Function.prototype.apply 这样的函数
例如:
const add = (x, y) => x + y
console.log(add.call(undefined, 3, 4));
关于javascript - 将箭头函数附加到另一个箭头函数是不好的做法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52149998/