箭头函数与普通function的区别

1. 箭头函数没有自己的this,它里面的this是继承所属上下文中的this,而且使用call与apply都无法改变 let obj = { name: 'obj' } function fn1() { console.log(this); } fn1.call(obj); let fn2() => { console.log(this); } fn2.call(obj); 2. 普通函数的参数是arguments,而箭头函数是arg let arr = [1,2,3] ~function(){ console.log(arguments); } (arr); //输出 [1,2,3] let a = (...arg) => { console.log(arg); } a(arr) //输出[1,2,3] 3. 语法上比普通函数更加简洁 function fn1(x) { return function(y) { return x + y; } } let fn1 = x => y => x + y; 4. 箭头函数不能使用new生成构造函数,因为箭头函数没有prototype,而construct在prototype里面。 function Fn1() { this.x = 100; } let f1 = new Fn1; let Fn2 = () => { this.x = 200; } let f2 = new Fn2; //输出 Fn2 is not a constructor
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章