箭头函数是ES6引入的一种函数声明方式,使用=>
符号定义:
// 基本语法
const func = (参数) => { 函数体 };
// 单参数可省略括号
const square = x => x * x;
// 无参数需要空括号
const sayHello = () => "Hello World";
// 多参数必须使用括号
const add = (a, b) => a + b;
当函数体只有一个表达式时,可省略花括号和return关键字:
// 传统函数
function double(x) {
return x * 2;
}
// 箭头函数
const double = x => x * 2;
返回对象字面量时需要用圆括号包裹:
const createPerson = (name, age) => ({ name, age });
箭头函数最大的特点是不绑定自己的this
,而是继承上下文的this
:
const counter = {
count: 0,
// 传统函数
incrementTraditional: function() {
setTimeout(function() {
console.log(this.count++); // this指向window,结果为NaN
}, 1000);
},
// 箭头函数
incrementArrow: function() {
setTimeout(() => {
console.log(this.count++); // this指向counter对象,正确增加count
}, 1000);
}
};
// 错误用法
const person = {
name: '张三',
sayHi: () => {
console.log(`你好,我是${this.name}`); // this指向外部作用域
}
};
// 正确用法
const person = {
name: '张三',
sayHi() {
console.log(`你好,我是${this.name}`);
}
};
箭头函数不能用作构造函数,没有自己的this
,也没有prototype
属性:
const Person = (name) => {
this.name = name; // 错误,this不指向新创建的对象
};
// 错误:this不指向按钮元素
button.addEventListener('click', () => {
this.classList.toggle('active');
});
// 正确
button.addEventListener('click', function() {
this.classList.toggle('active');
});
const numbers = [1, 2, 3, 4, 5];
// map
const doubled = numbers.map(n => n * 2);
// filter
const evens = numbers.filter(n => n % 2 === 0);
// reduce
const sum = numbers.reduce((acc, n) => acc + n, 0);
const result = [1, 2, 3, 4, 5]
.filter(n => n % 2 === 0)
.map(n => n * 2)
.reduce((acc, n) => acc + n, 0);
const curry = fn => a => b => fn(a, b);
const add = (a, b) => a + b;
const curriedAdd = curry(add);
const add5 = curriedAdd(5);
const result = add5(3); // 8
箭头函数在某些场景下可提高性能:
class Counter extends React.Component {
state = { count: 0 };
// 使用箭头函数自动绑定this
increment = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<button onClick={this.increment}>
点击次数: {this.state.count}
</button>
);
}
}
// Promise链
fetchData()
.then(data => processData(data))
.then(result => displayResult(result))
.catch(error => handleError(error));
// Async/await与箭头函数结合
const loadData = async () => {
try {
const data = await fetchData();
const result = await processData(data);
return displayResult(result);
} catch (error) {
handleError(error);
}
};
箭头函数带来了更简洁的语法和词法绑定的this
,使JavaScript代码更加简洁优雅。但需要注意其使用场景的限制,合理选择传统函数和箭头函数,才能发挥各自的优势。