箭头函数与普通函数的区别是什么?构造函数(function)可以使用new生成实例,箭头函数可以吗?
1.箭头函数和普通函数的区别
(1)箭头函数语法上比普通函数更加简洁
(2)箭头函数没有自己的this,它里面出现this是继承函数所处上下文中的this,(使用call,apply等任何方式都无法改变this的指向)
(3)箭头函数中没有arguments(类数组),只能基于…ARG获取传递的参数集合
(4)箭头函数不能被new函数(因为:箭头函数没有this,也没有prototype)
注:回调函数的this一般指向window
document.body.onclick = () => {
console.log(this)//window
}
document.body.onclick = function() {
console.log(this)//body
}
扩展:
回调函数:把一个函数B作为实参传递给函数A,函数A在执行的时候,可以把传递进来的B去执行(执行N次,可传值,可改this)
function each(arr,callback){
for(let i = 0;i++;i<arr.length){
//接收回调函数返回的结果
let flag = callback.call(arr,i,arr[i])
}
}
each([10,20,30],function(index,item){
//this=>原始操作数组
return false
})