The difference between arrow function and function in ES6

1. Different writing methods

// How to write function
function fn(a, b){
    return a+b;
}
// The writing method of arrow function
let foo = (a, b) =>{ return a + b }

2. Different points of this

In function, this refers to the object calling the function;

//Functions defined with function
function foo(){
    console.log(this);
}
var obj = { aa: foo };
foo(); //Window
obj.aa() //obj { aa: foo }

In arrow functions, this always points to the environment in which the function is defined.

//Defining functions using arrow functions
var foo = () => { console.log(this) };
var obj = { aa:foo };
foo(); //Window
obj.aa(); //Window
function Timer() {
  this.s1 = 0;
  this.s2 = 0;
  // Arrow function
  setInterval(() => {
     this.s1++;
     console.log(this);
  }, 1000); // this here points to timer
  // Ordinary function
  setInterval(function () {
    console.log(this);
    this.s2++; // This here points to this in window
  }, 1000);
}

var timer = new Timer();

setTimeout(() => console.log('s1: ', timer.s1), 3100);
setTimeout(() => console.log('s2: ', timer.s2), 3100);
// s1: 3
// s2: 0

3. Arrow function cannot be a constructor

//Defining a constructor using the function method
function Person(name, age){
    this.name = name;
    this.age = age;
}
var lenhart =  new Person(lenhart, 25);
console.log(lenhart); //{name: 'lenhart', age: 25}
//Try arrow function
var Person = (name, age) =>{
    this.name = name;
    this.age = age;
};
var lenhart = new Person('lenhart', 25); //Uncaught TypeError: Person is not a constructor

In addition, because the arrow function does not have its own this, of course, you cannot use call(), apply(), bind() to change the direction of this.

4. Variable promotion

function has variable promotion, which can be defined after the call statement;

foo(); //123
function foo(){
    console.log('123');
}

Arrow function is assigned in literal form, and there is no variable promotion;

arrowFn(); //Uncaught TypeError: arrowFn is not a function
var arrowFn = () => {
    console.log('456');
};
console.log(f1); //function f1() {}   
console.log(f2); //undefined  
function f1() {}
var f2 = function() {}

Keywords: Javascript

Added by marschen on Wed, 04 Dec 2019 19:16:56 +0200