function和=>有什么区别?在TypeScript中? [英] What's the difference between function and => in TypeScript?
问题描述
目前,我正在学习TypeScript.我对关键字函数和=>(胖箭头)之间的区别感到很困惑.请参见下面的代码:
Currently, I am learning TypeScript. I am quite confused about the difference between keyword function and => (fat arrow). Please see the code below:
interface Counter {
(start: number);
interval: number;
reset() : void;
}
let a = <Counter>function(start: number) { };
let b = <Counter>(start: number) => { };
a.reset(); //OK
b.reset(); //error: Property 'reset' does not exist on type <Counter>(start: number) => void
胖箭头似乎与关键字功能不同.
It seems that fat arrow doesn't work the same as keyword function.
推荐答案
胖箭头函数的语法比函数表达式短,并且按词法绑定此值.箭头函数始终是匿名的,可以有效地将function (arguments) { return expression; }
转换为(arguments) => expression
.如果在箭头后面使用表达式,则返回值是隐式的,因此不需要返回值.
fat arrow functions have a shorter syntax compared to function expressions and lexically bind the this value. Arrow functions are always anonymous and effectively turn function (arguments) { return expression; }
into (arguments) => expression
. If using an expression after an arrow, the return is implicit, so no return is required.
这篇关于function和=>有什么区别?在TypeScript中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!