箭头函数与普通函数区别

1、箭头函数不能作为构造函数,不能使用new

        function Fn(name){
            this.name = name;
            this.age = 18;
            console.log("Fn中的this==>",this); //new Fn()
        }
        let fn = new Fn("哈哈");
        //箭头函数
        let Fn = ()=>{
            this.name = name;
            this.age = 18;
        }
        let fn = new Fn(); //报错:Fn is not a constructor

2、箭头函数的this,始终指向父级上下文

        let obj = {
            a: 100,
            fn: function(){
                console.log(this);//obj
            },
            fn2: ()=>{
                console.log("fn2====>",this);//window
            }
        };
        obj.fn();
        obj.fn2();

3、箭头函数不能通过call apply bind改变this指向,但是可以通过这些方法传递参数

        let obj = {
            name: "obj",
            birth: 1990,
            year: 2021,
            age: (arg1, arg2)=>{
                console.log(this);//window
                console.log(arg1, arg2);//obj2
                console.log("my age =", this.year - this.birth)
            }
        }
        let obj2 = {
            name: "obj2",
            birth: 2000,
            year: 2020,
        };
        obj.age.call(obj2,"参数1","参数2")

4、箭头函数没有arguments属性,可以用...展开运算符来接受所有的参数集合

        let fn = (...args)=>{
            // console.log(arguments);// arguments is not defined
            console.log(args);
        }
        fn(1,2,3)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值