是否将typescript函数或typescript常量引用导出到函数?
我是typescript新手,我正在质疑我继承的代码库中的一种模式:是否将typescript函数或typescript常量引用导出到函数?,typescript,Typescript,我是typescript新手,我正在质疑我继承的代码库中的一种模式: export const registerTubesReducer = handleTubeActions function handleTubeActions(previousState: ITubes, action: TubeAction): ITubes { 对 export function registerTubesReducer(previousState: ITubes, action: TubeActio
export const registerTubesReducer = handleTubeActions
function handleTubeActions(previousState: ITubes, action: TubeAction): ITubes {
对
export function registerTubesReducer(previousState: ITubes, action: TubeAction): ITubes {
除了样式之外,还有什么原因更喜欢导出常量而不是普通函数导出吗?在这种情况下没有什么大的区别。虽然第一个版本可以简化为
export const registerTubesReducer = (previousState: ITubes, action: TubeAction): ITubes => { ... }
要注意箭头函数和常规函数之间的差异 1) 箭头函数有一个词法绑定的
this
,它不随调用函数的方式而改变
2) 箭头函数不被提升,因为它们只是带有函数值的变量声明。在定义该函数之前,您将无法使用该函数,否则您将调用且未定义的变量
arrowAdd(1, 2) // arrowAdd will be undefined here
functionAdd(1,2) // All good since function declarations are hoisted
const arrowAdd = (a: number, b: number) => a + b
function functionAdd(a: number, b:number) {
return a + b
}
3) 如果只想返回值,则箭头函数允许您省略额外的大括号
关于箭头函数和常规函数之间的区别,有一个规范的答案,我不这么认为。看看是否有其他人有什么要添加的。函数和箭头函数的可能重复以不同的方式处理“this”。如果你意识到这一点,那么就没有什么可补充的了。我想说,第一次剪断是不好的,因为它在定义之前使用了“handleTubeActions”。