箭头函数

基本使用

  • 使用

      //箭头函数
      var f = v => v;
      //等同于
      var f = function(v){
          return v;
      } 
    

如果箭头函数不需要参数,或者是需要多个参数,就用圆括号代表参数部分。

	var f = () => 5;
	//等同于
	var f = function(){
	    return 5;
	}
	
	var sum = (num1, num2) => num1+num2;
	//等同于
	var sum = function(num1, num2){
	    return num1+num2;
	}
  • 好处:简化回调函数

      //箭头函数简化回调函数
      console.log([1, 2, 3].map( x => x*x));
    
  • 使用注意点

  1. 函数体内的this对象就是定义时所在的对象,而不是使用时所在的对象。也就是说,在箭头函数中this对象的指向不是可变的,而是固定的。

     	//箭头函数的this对象是固定的
     	function foo(){
     	    setTimeout( () => {
     	        console.log("id:", this.id);
     	    }, 100);
     	}
    
     	foo.call({id: 42});//call方法是基本引用类型function类型的一个实例,用于就是特定的作用域中调用函数,设置函数体内的this对象的值
    

箭头函数的this对象总是指向handler对象。

		var handler = {
		    id: "123456",
		
		    init: function(){
		        document.addEventListener("click", event => this.doSomething(event.type), false);
		    },
		
		    doSomething: function(type){
		        console.log("handing" + type +"for" + this.id);
		    }
		};
  1. 不可以当做构造函数。也就是说不可以使用new命令,否则出错。

     	function Timer(){
     	    this.seconds = 0;
     	    setInterval( () => this.seconds++, 1000);
     	};
     	var timer = new Timer();
     	console.log(setTimeout( () => console.log(timer.seconds), 3100));//3
    

箭头函数是没有自己的this的,所以函数内部的this都是外层代码的this,这也是他不能作为构造函数的原因。 当然,没有this对象也不可以使用call、apply、bind方法去改变this的指向
3. 不可以使用arguments对象,该对象在函数体内不存在,如果要用,可以用rest参数替代。除了这些,super、new.target这些指向外层函数的对应变量在箭头函数中都是不存在的。
4. 不可以使用yield命令,因为箭头函数不能作为generator函数。

原文地址:https://www.cnblogs.com/yehui-mmd/p/7397938.html