箭头函数总结

箭头函数总结

// 优点:
// 1. 更加简短的函数(匿名函数)
// 2. 更加直观的作用域和this绑定(不绑定this)

为什么用箭头函数

// 简短
// no this
// 箭头函数并没有它自己的执行上下,实际上,这就意味着代码中的this和arguments都是继承它的父函数。
const name = 'windowName'
const obj = {
    name: 'morning',
    addFn: function() {
        return () => {
            console.log(this.name);
            // morning
            console.log('this',this);
            // this { name: 'morning', addFn: [Function: addFn] }
            return this
        }
    }
}
const fn = obj.addFn()
// fn()

// 不绑定arguments
function foo(n,m) {
    const f = () => {
        console.log(arguments);
        // [Arguments] { '0': 1, '1': 2 }
        console.log(arguments[0]); // 1

    }
    return f()
}

// foo(1,2)

怎么用

// 用于优化代码:
// 1. 使用map时
// 2. 使用forEach 代替 for 时
// 3. promise and promise链时
// 4. 用于封装的对象转换

什么时候不使用

// 1. 使用new时
Foo = () => {};
// foo = new Foo()
// TypeError: Foo is not a constructor
// 箭头函数不能用作构造器

// 2. 使用prototype时
// console.log(Foo.prototype);
// undefined
// 箭头函数没有prototype属性

// 3. yield 生成器

// 4. 调试代码时 


常见错误

// 返回对象字面量
const fn1 = () => {a:1};
console.log(fn1()); // undefined
const fn2 = () => ({a:1});
console.log(fn2()); // { a: 1 }

箭头函数用作闭包

// 箭头函数用作闭包
// 标准闭包
function A() {
    let x = 1
    return function B() {
        return x + 1
    }
    
}
const fn3 = A()
console.log(fn3()); // 2
// 箭头函数闭包
const BiBao = (i = 1) => {
    return (() => {
        return (i + 1)
    })
};
// const BiBao1 = (i=1) => () => (i+1)
const fn4 = BiBao()
console.log('闭包',fn4()); // 闭包 2

MDN官网介绍

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值