Home  >  Article  >  Web Front-end  >  What is the difference between ES6 arrow functions and functions?

What is the difference between ES6 arrow functions and functions?

不言
不言forward
2019-03-13 13:40:332486browse

What this article brings to you is about the difference between ES6 arrow functions and functions? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Different writing methods

// function的写法
function fn(a, b){
    return a+b;
}
// 箭头函数的写法
let foo = (a, b) =>{ return a + b }

2.This points to different points

In function, this points to the object that calls the function;

//使用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.

//使用箭头函数定义函数
var foo = () => { console.log(this) };
var obj = { aa:foo };
foo(); //Window
obj.aa(); //Window
function Timer() {
  this.s1 = 0;
  this.s2 = 0;
  // 箭头函数
  setInterval(() => {
     this.s1++;
     console.log(this);
  }, 1000); // 这里的this指向timer
  // 普通函数
  setInterval(function () {
    console.log(this);
    this.s2++; // 这里的this指向window的this
  }, 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 functions cannot be used as constructors

//使用function方法定义构造函数
function Person(name, age){
    this.name = name;
    this.age = age;
}
var lenhart =  new Person(lenhart, 25);
console.log(lenhart); //{name: 'lenhart', age: 25}
//尝试使用箭头函数
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, since arrow functions do not have their own this, of course they cannot use call(), apply(), bind() These methods change the pointer of this.

4. Variable promotion

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

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

The arrow function assigns a value in the form of a literal, 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() {}

                                                                                               

The above is the detailed content of What is the difference between ES6 arrow functions and functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete