箭头函数
ES6 允许使用 箭头 =>
定义函数
箭头函数有几个使用注意点。
-
函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
-
不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。
-
不可以使用arguments对象,该对象在函数体内不存在。如果要用,可以用 rest 参数代替。
-
不可以使用yield命令,因此箭头函数不能用作 Generator 函数。
//之前的写法
let fu = function(){
}
//箭头函数的写法
let fun = (a,b) => {
return a+b;
}
let result = fun(1,2);
console.log(result);
和之前函数的区别
this
是静态的,this
始终指向函数声明时所在作用域下的this
的值
function getName(){
console.log(this.name);
}
let getName2 = () =>{
console.log(this.name);
}
window.name = '尚硅谷';
const school = {
name: "nihao"
}
//直接调用
getName(); //尚硅谷 普通函数直接调用 this指向window
getName2();//尚硅谷 在全局作用域下声明,也指向window
getName.call(school); //nihao
getName2.call(school); //尚硅谷 this指向没有改变
- 不能作为构造函数实例化对象,会报错
- 不能使用
arguments
对象 - 箭头函数的简写
- 省略小括号,当形参有且只有一个的时候
- 省略花括号,当代码体只有一条语句,此时
return
也必须省略,而且语句的结果就是函数的返回值
let add = n => {
return n + n;
}
console.log(add(9));//18
let pow = (n) => n*n;
console.log(pow(8));//64
箭头函数的实践及应用场景1—获取元素
let ad = document.getElementById('ad');
//绑定事件
ad.addEventListener("click",function(){
//定时器
setTimeout(function(){
//修改背景颜色 this
this.style.background = 'pink';
}, 2000);
})
无效 原因:this
指向window
window
没有backgroound
属性
解决:保存this
的值,之间的
let ad = document.getElementById('ad');
//绑定事件
ad.addEventListener("click",function(){
//保存this的值
let _this = this;
//定时器
setTimeout(function(){
//修改背景颜色 this
_this.style.background = 'pink';
}, 2000);
})
解决方法2:使用箭头函数
let ad = document.getElementById('ad');
//绑定事件
ad.addEventListener("click",function(){
//定时器
setTimeout(() => {
//修改背景颜色 this
this.style.background = 'pink';
}, 2000);
})
有效原因:this是静态的,它指向的是声明时所在的作用域下this的值
箭头函数的实践及应用场景2—从数组中返回偶数的元素
之前的写法
const arr = [1,6,9,10,100,25];
const result = arr.filter(function(item){
if(item % 2 ===0 ){
return true;
}else {
return false;
}
});
console.log(result);// (3)[6,10,100]
用箭头函数
const arr = [1,6,9,10,100,25];
const result = arr.filter(item => {
if(item % 2 ===0 ){
return true;
}else {
return false;
}
});
console.log(result);
简化箭头函数
const arr = [1,6,9,10,100,25];
const result = arr.filter(item => item % 2 === 0);
console.log(result);
箭头函数适合与this无关的回调。 定时器,数组的方法回调
箭头函数不适合与 this 有关的回调。 事件回调,对象的方法
{
name: '尚硅谷',
getName: () => {
this.name;
}
}
此时this不指向对象,而指向外层作用域this的值,只是不适合,不是不能
箭头函数写快排
var array = [2,3,5,23,123];
const quickSort = array => {
if(array.length <= 1){
return array;
}
let [pivot,...rest] = array;
return [
...quickSort(rest.filter(i => i <= pivot)),
pivot,
...quickSort(rest.filter(i => i > pivot)),
]
}