Function arrow (=>)

ES6 allows the use of "arrow" (=>) defined function.

A. Arrow function

1. Basic definitions

  • ① simple wording, a variable expression that returns a single value

    var f = v => v;
    
    // 等同于
    var f = function (v) {
      return v;
    };
    
  • ② empty parameters

    var f = () => 5;
    // 等同于
    var f = function () { return 5 };
    
  • ③ multi-parameter

    	var sum = (num1, num2) => num1 + num2;
    // 等同于
    var sum = function(num1, num2) {
      return num1 + num2;
    };
    
  • ④ body of the function in multiple statements, use the returnstatement to return and use braces to surround the function body.

    var sum = (num1, num2) => { 
    	num1+=1;
    	return num1 + num2; }
    
  • ⑤ structure function may not return

    //一 单行不返回使用void关键字标识
    let fn = () => void doesNotReturn();
    // 二 多行语句不使用return
    var sum = (num1, num2) => { 
    num1+=1;
    num1 + num2; }
    
  • If the arrow ⑥ function to return directly to an object, since the braces is interpreted as code blocks, objects outside the parentheses must avoid an error.

    // 报错
    let getTempItem = id => { id: id, name: "Temp" };
    
    // 不报错
    let getTempItem = id => ({ id: id, name: "Temp" });
    

2. Arrow functions and variables used in conjunction deconstruction

  • Destruction and arrows variable function can be used in combination.

    	const full = ({ first, last }) => first + ' ' + last;
    
    // 等同于
    function full(person) {
      return person.first + ' ' + person.last;
    }
    

3. Use the arrow function example

  • Arrow function such that expression more concise.

    const isEven = n => n % 2 === 0;
    const square = n => n * n;
    
  • Simplify the callback function

    // 正常函数写法
    [1,2,3].map(function (x) {
      return x * x;
    });
    
    // 箭头函数写法
    [1,2,3].map(x => x * x);
    
    // 正常函数写法
    var result = values.sort(function (a, b) {
      return a - b;
    });
    
    // 箭头函数写法
    var result = values.sort((a, b) => a - b);
    
  • Examples of the arrow rest parameter binding function

    const numbers = (...nums) => nums;
    
    numbers(1, 2, 3, 4, 5)
    // [1,2,3,4,5]
    
    const headAndTail = (head, ...tail) => [head, tail];
    
    headAndTail(1, 2, 3, 4, 5)
    // [1,[2,3,4,5]]
    

II. Note the use of the arrows point function

1. The impact of this points to

  • this object represents the current context object to run the ordinary function has its own scope, the definition of this point is itself operating environment, if you run this function in an object that points to this object, if run in the big picture points to the global object ; scope and the object is not formed, if the object attribute defines this directly or using the arrow function definition (non-normal function), points to the higher operating environment (Object is the top most window)

     const cat = {
    	thisDefine: this,//object window
    	lives: 9,
    	jumps: () => {
    	  this.lives--;
    	  alert(this.lives)//NaN
    	},
    	jumps2: function () {
    	  this.lives--;
    	  alert(this.lives)//8
    	}
      }
      alert(cat.thisDefine)//object window
      cat.jumps()
      alert(cat.lives)//9
      cat.jumps2()
      alert(cat.lives)//8
    
  • Arrow vivo function this object, where the object is defined when, instead of when the object is located.

    //一 call方法使对象具有调用foo和foo2函数的能力
    //二 setTimeout的参数是一个箭头函数,这个箭头函数的定义生效是在foo函数生成时,而它的真正执行要等到 100 毫秒后。如果是普通函数,执行时this应该指向全局对象window,这时应该输出21。但是,箭头函数导致this总是指向函数定义生效时所在的对象(本例是{id: 42}),所以输出的是42。
    //三 箭头函数可以让setTimeout里面的this,绑定定义时所在的作用域,而不是指向运行时所在的作用域。
      var id = 21;
      function foo() {
    	setTimeout(() => {
    	  console.log('id:', this.id);
    	}, 100);
      }
    
      function foo2() {
    	setTimeout(function(){
    	  console.log('id:', this.id);
    	}, 100);
      }
      foo2.call({ id: 49 });
      //id: 21
      foo.call({ id: 42 });
      // id: 42
    

2. The arrow can not function as a constructor

  • Not as a constructor, that is, not using the new command, otherwise it will throw an error.

3. The function does not own this arrow, pointing to this object the outer layer

  • Arrow function in thisreal terms: thispoint of immobilization, not because there is an internal mechanism to bind this function arrow, the actual reason is a function of the arrow did not own this, cause this is the inside of this outer code block. It is precisely because it does not have this, so it can not be used as a constructor.

    var handler = {
      id: '123456',
    
      init: function() {
    	document.addEventListener('click',
    	  event => this.doSomething(event.type), false);
      },
    
      doSomething: function(type) {
    	console.log('Handling ' + type  + ' for ' + this.id);
      }
    };
    
  • example

    //下面代码之中,只有一个this,就是函数foo的this,所以t1、t2、t3都输出同样的结果。因为所有的内层函数都是箭头函数,都没有自己的this,它们的this其实都是最外层foo函数的this。
    function foo() {
      return () => {
    	return () => {
    	  return () => {
    		console.log('id:', this.id);
    	  };
    	};
      };
    }
    
    var f = foo.call({id: 1});
    
    var t1 = f.call({id: 2})()(); // id: 1
    var t2 = f().call({id: 3})(); // id: 1
    var t3 = f()().call({id: 4}); // id: 1
    

4. In addition to the function of the arrow this, the arrow being a function of three variables are not present, the function corresponding to the outer point variables: arguments, super, new.target.

  • The arrow inside the function variable arguments, in fact, is the function foo arguments variable.

    function foo() {
      setTimeout(() => {
    	console.log('args:', arguments);
      }, 100);
    }
    
    foo(2, 4, 6, 8)
    // args: [2, 4, 6, 8]
    
  • As the arrow function does not own this, so of course we can not use call (), apply (), bind () methods to change the point of this.

    //箭头函数没有自己的this,所以bind方法无效,内部的this指向外部的this。
    (function() {
      return [
    	(() => this.x).bind({ x: 'inner' })()
      ];
    }).call({ x: 'outer' });
    // ['outer']
    

III. Use the arrow inappropriate scenes function

1. Since this function is such that an arrow from "dynamic" to "static", in essence, no internal this point, this refers to a superior object copy

  • The first case is a definition of an object method, and the method comprises the interior this.

    //因为对象不构成单独的作用域,导致jumps箭头函数定义时的作用域就是全局作用域this指向全局对象。jumps2定义在普通函数中,形成了作用域,this指向cat对象
      const cat = {
    	lives: 9,
    	jumps: () => {
    	  this.lives--;
    	  alert(this.lives)//NaN
    	},
    	jumps2: function () {
    	  this.lives--;
    	  alert(this.lives)//8
    	}
      }
      cat.jumps()
      alert(cat.lives)//9
      cat.jumps2()
      alert(cat.lives)//8
    
  • The second occasion is this dynamic when needed, nor should use the arrow functions.

    //下面代码运行时,点击按钮会报错,因为button的监听函数是一个箭头函数,导致里面的this就是全局对象。如果改成普通函数,this就会动态指向被点击的按钮对象。
    var button = document.getElementById('press');
    button.addEventListener('click', () => {
      this.classList.toggle('on');
    });
    
Published 170 original articles · won praise 61 · views 50000 +

Guess you like

Origin blog.csdn.net/NDKHBWH/article/details/103855858