4. 箭头函数

242 阅读2分钟

es6的箭头函数

es6使用 => 来定义函数,() => {} 等同于 function(){}

//es5写法
let add = function (a,b){
     return a + b;
}
//es6写法
let add = (a,b)=> {
    return a + b;
}
console.log(add(10,20))

箭头函数的简写

let fn = (a,b)=> { //两个参数这样写
    return a + b;
}
//----------------------------------------------------------
let fn = a => { //只有一个参数括号可以省略
    return a + 5;
}
//----------------------------------------------------------
let fn = (a,b) => a + b;
let fn = a => a + 5; // 如果只是简单的函数运算,大括号可以省略
//----------------------------------------------------------
let fn = ()=> 'helow'+'world'; //如果没有传参,需要保留()
console.log(fn())

省略return返回对象时需要在{}外需要加 ( ),以区分函数{}格式,否则会报错

let getObj = a => {
    return {
        id:a,
        name:'Max'
    }
}
//---------------------------------------------------------------
let getObj = a => ({  
    id: a, 
    name: 'Max'
});
console.log(getObj(1))// 打印结果 {id: 1, name: "Max"}

箭头函数的this指向

es5中的this指向,取决于调用该函数距离的最近对象

es6的箭头函数是没有this指向绑定的,箭头函数内部的this只能通过查找作用域链来确定,一旦使用箭头函数,当前就不存在作用域链,可以理解为this指向会跳过当前的调用对象向继续外层查找调用function函数的对象

let PageHandle = {
    id: 123,
    init: function () {
        document.addEventListener('click', function (event) {
            console.log(this);//这里的this指向了当前调用函数的document
            this.doSomeThings(event.type);
        }, false)
    },
    doSomeThings: function (type) {
        console.log(`事件类型:${type},当前id:${this.id}`);
    }
}
//----------------------------------------------------------------------
let PageHandle = {
    id: 123,
    init: function () { //函数对象声明的函数,不要使用箭头函数,否则会指向外层作用域
        document.addEventListener('click', (event) => {
            console.log(this);//这里的this指向了PageHandle对象
            this.doSomeThings(event.type);
        }, false)
    },
    doSomeThings: function (type) {
        console.log(`事件类型:${type},当前id:${this.id}`);
    }
}
PageHandle.init()

使用箭头函数的注意事项

  1. 使用箭头函数,函数内部没有arguuments

    let getVal = function (a, b) {
        console.log(this);// window
        console.log(arguments);// 有arguments对象
        return a + b;
    }
    let getVal = (a, b)=> {
        console.log(this);// window
        console.log(arguments);// arguments is not defined.没有arguments,调用就会报错
        return a + b;
    }
    console.log(getVal(3, 6));
    
  2. 箭头函数不能使用new关键字来实例化对象

    let Box = function () {
    
    }
    console.log(Box);// () => {  }
    
    let a = new Box();
    console.log(a);// Box{}__proto__: Object
    //------------------------------------------------------
    let Box = () => {
    
    }
    console.log(Box);// () => {  }
    
    let a = new Box();
    console.log(a);//Box is not a constructor.Box不是构造函数