箭头函数与普通函数function的区别是什么?构造函数(function)可以使用new生城实例,那么箭头函数可以吗?为什么?
从箭头函数与普通函数区别入手
1.箭头函数语法比普通函数更加简洁
普通函数: function fn(){ return function(){ return x+y; } } 箭头函数: let fn = x => y => x + y ;
2.箭头函数没有自己的this,它里面的this是继承上下文中的this,使用call/apply/bind等任何方式都无法改变this的指向
普通函数: let obj = {name:'lili'}; function fn1(){ console.log(this); } fn1.call(obj); //{name:'lili'} 箭头函数: let fn2 = () => {console.log(this)} fn2.call(obj); //window
3.箭头函数没有arguments(类数组),但是可以基于…arg获取传递的参数集合并且获取到的参数集合是数组;
普通函数: let obj = {name:'lili'}; function fn1(){ console.log(arguments); } fn1(10,20,30);// Arguments(3) [10, 20, 30, length:3, callee:fun... 箭头函数: let fn2 = (...arg) => { console.log(arguments); //Uncaught ReferenceError: arguments is not defined console.log(arg);//[10,20,30] } fn2(10,20,30);
4.箭头函数不能被new执行(因为:建有函数没有this,也没有prototype);
普通函数: function Fn(){ this.x = 100; } Fn.prototype.getx = function(){return this.x}; let f = new Fn(); console.log(f);//{x:100}; console.log(f.getx()); //100 箭头函数: let Fn2 = () => { this.x = 100; } let f2 = new Fn2();//Uncaught TypeError: Fn2 is not a constructor