我们知道函数声明已被提升,您可以在脚本中的任何位置调用它们。函数表达式不是这种情况。
例如:
test();
const test = () => {
console.log(1+3);
}
When we call test() it will always return undefined.
Run Code Online (Sandbox Code Playgroud)
但是,当我们在expressjs中间件中调用相同的函数时,不会发生这种情况。
router.get('/', (req, res, next) => {
test(); // it will return always the result 4
})
const test = () => {
console.log(1+3);
}
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释为什么会这样吗?