箭头函数
箭头函数提供了更简洁的函数语法,且不绑定自己的 this。
基本语法
标准形式
JavaScript
// 传统函数
const add = function(a, b) {
return a + b;
};
// 箭头函数
const add = (a, b) => {
return a + b;
};
简写形式
单参数省略括号:
JavaScript
const double = n => n * 2;
单表达式省略return:
JavaScript
const add = (a, b) => a + b;
无参数:
JavaScript
const sayHi = () => console.log('Hi');
返回对象需加括号:
JavaScript
const createUser = name => ({ name, age: 18 });
this绑定
箭头函数没有自己的 this,继承外层作用域的 this:
JavaScript
const obj = {
name: 'Tom',
// 传统函数:this指向调用者
greetTraditional: function() {
console.log(this.name); // Tom
},
// 箭头函数:this继承外层
greetArrow: () => {
console.log(this.name); // undefined(外层this是window/undefined)
}
};
解决回调中的this问题
JavaScript
function Timer() {
this.seconds = 0;
// 传统写法
setInterval(function() {
this.seconds++; // this指向window,报错
}, 1000);
// 箭头函数
setInterval(() => {
this.seconds++; // this正确指向Timer实例
}, 1000);
}
不适用场景
对象方法
JavaScript
const obj = {
name: 'Tom',
greet: () => console.log(this.name) // 错误:this不是obj
};
// 正确写法
const obj = {
name: 'Tom',
greet() { console.log(this.name); } // 方法简写
};
构造函数
JavaScript
const Person = (name) => {
this.name = name; // 错误:没有this
};
const p = new Person('Tom'); // TypeError
事件处理器
JavaScript
button.addEventListener('click', () => {
console.log(this); // this不是button
});
// 正确写法
button.addEventListener('click', function() {
console.log(this); // this是button
});
原型方法
JavaScript
function Person(name) {
this.name = name;
}
Person.prototype.greet = () => {
console.log(this.name); // 错误:this不是实例
};
// 正确写法
Person.prototype.greet = function() {
console.log(this.name);
};
其他特性
没有arguments
JavaScript
const fn = () => {
console.log(arguments); // ReferenceError
};
// 使用剩余参数替代
const fn = (...args) => {
console.log(args);
};
没有prototype
JavaScript
const fn = () => {};
console.log(fn.prototype); // undefined
不能作为Generator
JavaScript
const fn = *() => {}; // SyntaxError
箭头函数vs传统函数
| 特性 | 箭头函数 | 传统函数 |
|---|---|---|
| this | 词法绑定 | 动态绑定 |
| arguments | 无 | 有 |
| prototype | 无 | 有 |
| 构造函数 | 不能 | 可以 |
| yield | 不能 | 可以 |
| 语法 | 简洁 | 冗长 |
要点总结
- 箭头函数语法简洁,单表达式可省略
return - 返回对象需用括号
({}) - 没有自己的
this,继承外层作用域 - 不适用:对象方法、构造函数、事件处理器
- 没有
arguments,用剩余参数替代
📝 发现内容有误?点击此处直接编辑