ES6之箭头函数

49 阅读2分钟

ES6之箭头函数

箭头函数可以说是ES6最成功的升级之一了。它解决了this指向的问题,并且方便了函数的使用。
比如下面这个例子:

const obj = {
    name: 'zhangsan',
    age: 18,
    sayHello: function () {
        const _this = this;
        setInterval(function(){
            console.log(_this.name, _this.age)
        }, 1000);
    },
    clickEvent:function(){
        const _this = this;
        window.onclick = function(){
            console.log(_this.name, _this.age)
        }
    }
}
obj.sayHello()
obj.clickEvent()

这个例子中,如果我们不使用_this,而使用this,那么两个函数的this都会指向window。所以我们通过设定一个固定的变量来解决。而使用箭头函数则可以完美的解决。箭头函数里的this只和定义时的位置有关系,而和调用时完全无关。所以在计时器和事件函数中,由于箭头函数是一个函数表达式,所以sayHello的this和setInterval的this一样,因为是普通对象调用,都指向obj对象。

const obj = {
    name: 'zhangsan',
    age: 18,
    sayHello: function () {
        // const _this = this;
        setInterval(()=>{
            console.log(this.name, this.age)
        }, 1000);
    },
    clickEvent:function(){
        // const _this = this;
        window.onclick = ()=>{
            console.log(this.name, this.age)
        }
    },
    print:function(){
        console.log(this)
        console.log(this.name, this.age)
    }
}
obj.sayHello()
obj.clickEvent()
obj.print()

// const print=obj.print;
// print()

下面是箭头函数的一些简写格式:

//判断一个数是否是奇数
// const isOdd=function isOdd(num) {
//     return num % 2 === 1;
// }
// const isOdd=num=>{
//     return num % 2 === 1;
// }
const isOdd = num => num % 2 === 1;
const sum=(a,b)=>({
    a,
    b,
    sum:a+b
})
console.log(sum(1,2))

注意:当我们只有一条语句并且想要返回一个对象时,这个对象必须变为表达式的形式,也就是在外面加一个括号。否则会错误地识别为函数体的大括号,导致报错。

const obj={
    print:()=>{
        console.log(this)
    }
}
obj.print() //window
const obj2={
    method:function (){
        print=()=>{
            console.log(this) //method对象
            console.log(arguments) //123
        }
        print()
    }
}
obj2.method(123)

如果对象的属性是一个箭头函数,则在指向window,如果是函数内有一个箭头函数,会和外层函数的指向相同。
我们一直说箭头函数只和定义有关,和如何调用无关。细细一想,当我们调用一个函数时,也是会回到函数的声明的位置。不论是哪种函数,都会看它的结构。当自身不是一个函数时,或者说只是一个临时函数,就会使用外层函数的情况。如果外层是window,那就只能指向window。
箭头函数的特点:

  • 不存在this,arguments,new.target,直接使用外层函数
  • 没有原型
  • 不能作为构造函数调用 所以,它的使用场景多用于:
  • 临时性函数,不需要调用(事件处理函数,异步函数)
  • 需要绑定外层函数的this
  • 也可以使用在数组的回调方法中
const result=[1,2,3,4,5].filter(num=>num%2===0).map(num=>num*2).reduce((a,b)=>a+b)
console.log(result)