New ways to define functions in ES6.

() = > {}//() : represents a function; => : required symbol, which code block to point to; {} : function body
const fn = () = > {}// assigns a function to fn
Copy the code

There is only one line of code in the function body, and the result of the code execution is the return value. You can omit the curly braces

 function sum(num1, num2) { 
     return num1 + num2; 
 }
 / / es6 writing
 const sum = (num1, num2) = > num1 + num2; 

Copy the code

If the parameter has only one, you can omit the parentheses

 function fn (v) {
     return v;
 } 
/ / es6 writing
 const fn = v= > v;

Copy the code

The arrow function is not bound to the this keyword. The this in the arrow function refers to the context this where the function is defined

const obj = { name: 'Joe'} 
 function fn () { 
     console.log(this);// This points to an obj object
     return () = > { 
         console.log(this);// This points to the position defined by the arrow function, so the arrow function is defined inside fn, and fn points to obj, so this also points to obj}}const resFn = fn.call(obj); 
 resFn();

Copy the code

1. Summary

  • The arrow function does not bind this. The this in the arrow function points to the position it defines
  • The advantage of the arrow function is that it solves some of the problems caused by the this execution environment. For example, the problem of anonymous function this pointing to (anonymous function execution environment is global), including setTimeout and setInterval caused by the use of this

2. The interview questions

var age = 100;

var obj = {
	age: 20.say: () = > {
		alert(this.age)
	}
}

obj.say();// The arrow function this points to the declared scope, while the object has no scope, so the arrow function is defined in the object, but this points to the global scope
Copy the code