在 TypeScript(也包括 JavaScript)中,=> 是 箭头函数(Arrow Function) 的语法,用来定义一个匿名函数,也叫“箭头函数表达式”。
const fn = (参数) => {
// 函数体
};
比如:
const add = (a: number, b: number): number => {
return a + b;
};
等价于传统写法:
function add(a: number, b: number): number {
return a + b;
}
如果函数体只有一行并且是返回值,可以省略 {} 和 return:
const square = (x: number) => x * x;
相当于:
const square = (x: number) => {
return x * x;
};
需要加空括号:
const sayHi = () => console.log('Hi');
可以省略括号(但建议加上):
const double = x => x * 2; // 可以,但不推荐
| 特性 | 箭头函数(=>) | 普通函数(function) |
|---|---|---|
| this 绑定 | 不绑定,继承外部作用域的 this |
根据调用方式动态绑定 |
| 构造函数 | 不能作为构造函数,不能使用 new |
可以作为构造函数 |
| arguments | 没有 arguments 对象 |
有 arguments 对象 |
例如:
const obj = {
name: "Tom",
sayHi: function () {
console.log("Hello", this.name); // this.name 是 Tom
},
sayHiArrow: () => {
console.log("Hello", this.name); // this 指向外部(非 obj),所以是 undefined
}
};
obj.sayHi(); // Hello Tom
obj.sayHiArrow(); // Hello undefined
写回调函数:
[1, 2, 3].map(x => x * 2);
如果你看到一个类似:
const greet: Greet = (name) => `Hello, ${name}`;
这表示:
Greet 是一个类型(通常是一个函数类型)name,返回一个字符串。