「日更_ES6」1. 箭头函数

89 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第2天,点击查看活动详情

前言: 积跬步第一天,该专栏争取日日更新

箭头函数的声明和调用:

// ES6 允许使用「箭头」(=>)定义函数。
//声明一个函数
let fn = (a,b) => {
    return a + b;
}
//调用函数
let result = fn(1, 2);

箭头函数声明的特性:

  1. this 是静态的. this 始终指向函数声明时所在作用域下的 this 的值
// 举例:
function getName(){
    console.log(this.name);
}//普通函数
let getName2 = () => {
    console.log(this.name);
}//箭头函数

//设置 window 对象的 name 属性
window.name = '晴天蜗牛';
const selfName = {
    name: "snail"
}

//直接调用 
getName(); // 晴天蜗牛 直接调用 this指向window
getName2(); // 晴天蜗牛 箭头函数因为在全局作用域下

//call 方法调用 可以改变函数this指向
getName.call(selfName); // snail this指向发生改变 
getName2.call(selfName); // 晴天蜗牛 this是静态的 this始终指向声明时所在作用域下的this值
  1. 不能作为构造实例化对象
// 举例:
let Person = (name, age) => {
    this.name = name;
    this.age = age;
}
let me = new Person('xiao',30);
console.log(me); // 报错 Person is not a constructor
  1. 不能使用 arguments 变量
let fn = () => {
    console.log(arguments);
}
fn(1,2,3); // arguments is not defind
  1. 箭头函数的简写
1) 省略小括号, 当形参有且只有一个的时候
let add = n => {
    return n + n;
}

2) 省略花括号, 当代码体只有一条语句的时候, 此时 return 必须省略,而且语句的执行结果就是函数的返回值
let pow = n => n * n;

案例:

  1. 需求-1 点击 div 2s 后颜色变成『粉色』
let ad = document.getElementById('ad');
ad.addEventListener("click", function(){
    // let _this = this; // 普通函数将外层作用域下的this进行保存
    setTimeout(() => {
        // console.log(this);
        // _this.style.background = 'pink';
        this.style.background = 'pink'; // this直接指向ad
    }, 2000);
});
  1. 需求-2 从数组中返回偶数的元素
const arr = [1,6,9,10,100,25];

// 普通函数
const result = arr.filter(function(item){
        if(item % 2 === 0){
            return true;
        }else{
            return false;
        }
      });
      
// 箭头函数
const result = arr.filter(item => item % 2 === 0);

console.log(result);

总结:

1.箭头函数适合与 this 无关的回调. 定时器, 数组的方法回调
2.箭头函数不适合与 this 有关的回调.  事件回调, 对象的方法