ES6精讲02-箭头函数

171 阅读2分钟

1.箭头函数与传统函数

  • 箭头函数:()=>{}
  • 传统函数:function(){}
// 传统函数
let add = function (a, b) {
    return a + b;
} 
// 箭头函数
let add = (a, b) => {
    return a + b;
}
let add = (val1, val2) => val1 + val2;
console.log(add(10, 20));
				
// 箭头函数省略return的写法
let fn = ()=> 'hello world' + 123;
console.log(fn());
				
// (传统)输入id,返回一个对象       
let getObj = id => {
    return {
        id: id,
        name:'小马哥'
    }
}

 // (ES6)的操作
 let getObj = id => ({id:id,name:"小马哥"});
 let obj = getObj(1);
 console.log(obj); //也是返回一个和上面例子一样的对象
			
// (传统)自执行函数
 let fn = (function() {
    return function() {
        console.log('hello es6');
    }
})();
fn()//hello es6

//(ES6)
let fn = (() => {
    return () => {
        console.log('hello es6 2');
    }
})();
fn(); // hello es6 2

2.箭头函数的this

// 没有this绑定
// es5中this指向:取决于调用该函数的上下文对象
 let PageHandle = {
    id: 123,
    init: function () {
        document.addEventListener('click',function(event) {
            // this.doSomeThings is not a function
             console.log("我是当前的dangthis",this);   //this是指向文档的,document
                  
            //Uncaught TypeError: this.doSomeThings is not a function at HTMLDocument
             this.doSomeThings(event.type);
                })
            },
            doSomeThings:function(type){
                console.log(`事件类型:${type},当前id:${this.id}`);
            }
        }
 PageHandle.init(); 

使用箭头函数的解决方法:

let PageHandle = {
    id: 123,
    init: function () {
        // 箭头函数没有this指向,箭头函数内部this值只能通过查找作用域链来确定,一旦使用箭头函数,当前就不存在作用域链
          document.addEventListener('click', (event) => {
              console.log(this); //这里的this指向的是PageHandle这个对象
              this.doSomeThings(event.type); 
          }, false)
      },
    doSomeThings: function (type) {
        console.log(`事件类型:${type},当前id:${this.id}`);//事件类型:click,当前id:123

    }
}
PageHandle.init();
  • 箭头函数没有this指向,箭头函数内部this值只能通过查找作用域链来确定

3.箭头函数的注意事项

// 使用箭头函数的注意事项1:使用箭头函数 函数内部没有arguments
let getVal = (a, b) => {
    console.log(arguments);  //Uncaught ReferenceError: arguments is not defined
    return a + b;
}
console.log(getVal(1, 3));
  • 箭头函数内部没有arguments:Uncaught ReferenceError: arguments is not defined
  • 箭头函数不能使用new关键字来实例化对象
let Person = ()=>{      
};
// function函数 也是一个对象,但是箭头函数不是一个对象,它其实就是一个语法糖
console.log(Person); //()=>{}
        
let p = new Person();//Uncaught TypeError: Person is not a constructor