ES6箭头函数与普通函数的区别
2015年6月正式发布的JavaScript语言的标准,正式名为ECMAScript 2015,简写为:ES2015,即是ES6。ES6中箭头函数我们做前端的常用常见,不仅要掌握且还要熟练使用箭头函数,下面概况总结下ES6箭头函数与普通函数的区别。

01.写法不同,箭头函数更简洁
// 箭头函数
let t = ()=>{
return 0;
}
// 普通函数
function t(){
return 0;
}02.箭头函数没有原型属性
var a = ()=>{
return 1;
}
function b(){
return 2;
}
console.log(a.prototype); // undefined
console.log(b.prototype); // {constructor: ƒ}03.箭头函数不绑定this,会捕获其所在的上下文的this值,作为自己的this值
箭头函数中this的指向不同,this一直是让初学者比较头疼,箭头函数的this永远指向其上下文的this,没有办改变其指向。
var myObject = {
value:1,
getValue:function(){
console.log(this.value)
},
double:function(){
return function(){ //this指向double函数内不存在的value
console.log(this.value = this.value * 2);
}
}
}
/*希望value乘以2*/
myObject.double()(); //NaN
myObject.getValue(); //104.箭头函数不能使用new
箭头函数全都是匿名函数,也不能用于构造函数
var B = ()=>{ value:1; }
var b = new B(); //TypeError: B is not a constructor05.箭头函数不具有arguments对象:
每一个普通函数调用后都具有一个arguments对象,用来存储实际传递的参数,但是箭头函数并没有此对象
/*常规函数使用arguments*/
function test1(a){
console.log(arguments); //1
}
/*箭头函数不能使用arguments*/
var test2 = (a)=>{console.log(arguments)} //ReferenceError: arguments is not defined
/*箭头函数使用reset参数...解决*/
let test3=(...a)=>{console.log(a[1])} //22
test1(1);
test2(2);
test3(33,22,44);06.箭头函数不能换行
07.箭头函数不能当做Generator函数,不能使用yield关键字
08.不能简单返回对象字面量
09.使用call()和apply()调用
10.箭头函数不具有super
11.箭头函数不具有new.target
除注明外的文章,均为来源:老汤博客,转载请保留本文地址!
原文地址:https://tangjiusheng.cn/js/199.html
原文地址:https://tangjiusheng.cn/js/199.html
