# 箭头函数

# 目录

  1. 基础概念
  2. 语法形式
  3. this绑定特性
  4. 实际应用

# 箭头函数基础概念

# 什么是箭头函数

箭头函数是ES6引入的一种新的函数语法,使用=>符号定义,提供了更简洁的函数写法和不同的this绑定规则。

# 与传统函数的区别

//传统函数
function add(a, b) {
    return a + b;
}

//箭头函数
const add = (a, b) => a + b;

//调用方式相同
console.log(add(2, 3)); // 5

# 箭头函数语法形式

# 基本语法

//单参数
const square = x => x * x;
console.log(square(5)); // 25

//多参数
const add = (a, b) => a + b;
console.log(add(2, 3)); // 5

//无参数
const greet = () => 'Hello World';
console.log(greet()); // Hello World

//多行函数体
const multiply = (a, b) => {
    const result = a * b;
    return result;
};
console.log(multiply(4, 5)); // 20

# 返回对象字面量

//需要加括号避免解析错误
const createUser = (name, age) => ({
    id: Math.random().toString(36).substr(2, 9),
    name,
    age,
    createdAt: new Date()
});

console.log(createUser('张三', 25));

# 参数默认值和解构

//参数默认值
const calculate = (a, b = 10) => a + b;
console.log(calculate(5)); // 15

//参数解构
const getUserInfo = ({ name, age }) => `${name}今年${age}`;
const user = { name: '李四', age: 30 };
console.log(getUserInfo(user)); //李四今年30岁

//复杂解构
const processData = ([first, second], { multiplier = 1 }) => ({
    sum: (first + second) * multiplier,
    average: (first + second) / 2
});

console.log(processData([10, 20], { multiplier: 2 })); // { sum: 60, average: 15 }

# this绑定特性

# 传统函数的this绑定

const obj = {
    name: '测试对象',
    traditionalFunction: function() {
        console.log('传统函数this:', this.name); //测试对象
        setTimeout(function() {
            console.log('传统函数内部this:', this.name); // undefined (指向window)
        }, 100);
    }
};

obj.traditionalFunction();

# 箭头函数的this绑定

const obj = {
    name: '测试对象',
    arrowFunction: function() {
        console.log('外层函数this:', this.name); // 测试对象
        setTimeout(() => {
            console.log('箭头函数this:', this.name); // 测试对象 (继承外层this)
        }, 100);
    }
};

obj.arrowFunction();

# 实际应用对比

//事件处理中的this绑定问题
class ButtonHandler {
    constructor() {
        this.clickCount = 0;
    }
    
    //传统方法 -需要bind
    handleTraditionalClick() {
        document.addEventListener('click', function() {
            this.clickCount++; // this指向document
            console.log('传统方法计数:', this.clickCount);
        }.bind(this));
    }
    
    //箭头函数方法 - 自动绑定
    handleArrowClick() {
        document.addEventListener('click', () => {
            this.clickCount++; // this正确指向实例
            console.log('箭头函数计数:', this.clickCount);
        });
    }
}

//数组方法中的应用
const numbers = [1, 2, 3, 4, 5];
const obj = {
    multiplier: 2,
    traditionalMap: function() {
        const self = this;
        return numbers.map(function(num) {
            return num * self.multiplier;
        });
    },
    arrowMap: function() {
        return numbers.map(num => num * this.multiplier);
    }
};

console.log(obj.traditionalMap()); // [2, 4, 6, 8, 10]
console.log(obj.arrowMap()); // [2, 4, 6, 8, 10]

# 箭头函数的实际应用场景

# 数组方法

const users = [
    { name: '张三', age: 25, salary: 8000 },
    { name: '李四', age: 30, salary: 12000 },
    { name: '王五', age: 28, salary: 10000 }
];

// filter
const youngUsers = users.filter(user => user.age < 30);
console.log('年轻用户:', youngUsers);

// map
const userNames = users.map(user => user.name);
console.log('用户姓名:', userNames);

// reduce
const totalSalary = users.reduce((sum, user) => sum + user.salary, 0);
console.log('总薪资:', totalSalary);

// sort
const sortedByAge = users.sort((a, b) => a.age - b.age);
console.log('按年龄排序:', sortedByAge);

# Promise和异步操作

// Promise链式调用
function fetchUserData(userId) {
    return fetch(`/api/users/${userId}`)
        .then(response => response.json())
        .then(user => {
            return fetch(`/api/users/${userId}/posts`)
                .then(response => response.json())
                .then(posts => ({ user, posts }))
        })
        .catch(error => {
            console.error('获取用户数据失败:', error);
            throw error;
        });
}

// async/await with arrow functions
const processUserData = async (userId) => {
    try {
        const userData = await fetchUserData(userId);
        const processedData = {
            ...userData.user,
            postCount: userData.posts.length,
            averagePostLength: userData.posts.reduce((avg, post) => 
                avg + post.content.length / userData.posts.length, 0
            )
        };
        return processedData;
    } catch (error) {
        console.error('处理用户数据失败:', error);
        throw error;
    }

# 事件处理

class EventManager {
    constructor() {
        this.eventCount = 0;
        this.init();
    }
    
    init() {
        //DOM事件处理
        document.addEventListener('click', (event) => {
            this.eventCount++;
            console.log(`点击事件 #${this.eventCount}`, event.target);
        });
        
        //定时器
        setInterval(() => {
            console.log(`当前事件计数: ${this.eventCount}`);
        }, 1000);
    }
}

// React组件示例
const UserProfile = ({ userId }) => {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);
    
    useEffect(() => {
        const fetchUser = async () => {
            try {
                const response = await fetch(`/api/users/${userId}`);
                const userData = await response.json();
                setUser(userData);
                setLoading(false);
            } catch (error) {
                console.error('获取用户失败:', error);
                setLoading(false);
            }
        };
        
        fetchUser();
    }, [userId]);
    
    if (loading) return <div>加载中...</div>;
    if (!user) return <div>用户不存在</div>;
    
    return (
        <div>
            <h2>{user.name}</h2>
            <p>年龄: {user.age}</p>
            <button onClick={() => console.log('用户详情:', user)}>
                查看详情
            </button>
        </div>
    );
};
# 高阶函数
//函数工厂
const createMultiplier = (multiplier) => (number) => number * multiplier;
const double = createMultiplier(2);
const triple = createMultiplier(3);

console.log(double(5)); // 10
console.log(triple(5)); // 15

//函数组合
const compose = (f, g) => (x) => f(g(x));
const addOne = (x) => x + 1;
const multiplyByTwo = (x) => x * 2;
const addOneThenMultiply = compose(multiplyByTwo, addOne);

console.log(addOneThenMultiply(5)); // 12

//柯里化
const multiply = (a) => (b) => a * b;
const multiplyByFive = multiply(5);
console.log(multiplyByFive(3)); // 15
本章目录