箭头函数和普通函数有什么区别?

1.箭头函数是匿名函数 箭头函数不能作为构造函数使用 不能使用new

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

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

4.箭头函数没有原型属性

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

一、箭头函数没有自己的this对象

箭头函数的this是在定义函数时绑定的,不是在执行过程中绑定的,箭头函数内的this就是箭头函数外的那个this

var a = '自行车'; 
var abc = {
  a: '阿道夫',
  say: () => {
    console.log(this.a)
  }
}
abc.say(); //自行车;

二、不能当作构造函数

不能对箭头函数使用new命令,否则会抛出一个错误。

使用function 关键字创建的函数是构造函数,箭头函数不能当构造函数进行使用

let fn1 = () => {};
let fn2 = function() {};
let f1 = new fn1(); // fn1 is not a constructor
let f2 = new fn2();

三、不能使用arguments对象

var a = '自行车'; 
var abc = {
  a: '阿道夫',
  say: () => {
    console.log(arguments) // arguments is not defined
  }
}
abc.say(); //自行车;



//可以用...展开运算符来接受所有的参数集合
// arguments 是参数集合 是一个类数组 不能调用数组的方法
    {
       function fn(){
            console.log(arguments);
           //谁在调用当前的方法 会返回这个方法本身
        }
        fn(1,2,3)

        let fn = (...args)=>{ 
//使用展开运算符接受参数集合
            console.log(arguments);
// arguments is not defined
            console.log(args); 
//是数组
        }
        fn(1,2,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")

    }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值