Skip to main content

ES6 arrow functions

 In ES6, in addition to the new features of let and const, arrow functions are the most frequently used new features. But this feature is not unique to ES6. Arrow functions, as the name suggests, are functions defined using arrows (=>) and belong to a class of anonymous functions. It allows us to write smaller function syntaxes. The code of arrow functions is simpler and more flexible to write.

The content of the article will introduce arrow functions from the following aspects:

  • Basic usage
  • specific characteristics

Basic usage:
  • Declarative functions cannot be abbreviated, only function expressions can be abbreviated.
let fun1=function(a,b){};
  let fun2=(a,b)=>{};
  let obj={
    fun1:function(a,b){},
    fun2:(a,b)=>{}
  }
  • When there is only one formal parameter of the function, you can not write () in other cases, you must write.
let fun=a=>{console.log("1111")}
  • Omit curly braces. When there is only one statement in the code body, return must be omitted.
  let fun3=a=>console.log("666");
  let fun4=b=>b+b;

specific characteristic:
  • this is static. this always points to the context's this.
  window.id=500;
  let id=100;//var id=100,then it will overwrite the value of window
  let obj={
    id:200
  }
  let fun1=function(){
    console.log(this.id,this);
  }
  let fun2=()=>{
    console.log(this.id,this);
  }
  fun1.call(obj);//200,{id:200}
  fun2.call(obj);//500,Window
  var id=500;//or window.id=500;
  let obj={
    id:100,
    fun1:function(){
        console.log(this.id,this);
    },
    fun2:()=>{
        console.log(this.id,this);
    }
  }
  obj.fun1();//100,object....
  obj.fun2();//500,Window
  • cannot be used as a constructor
  let A=(age,name)=>{
    this.age=age;
    this.name=name;
  }
  let a=new A(10,"aaa");//Uncaught TypeError: A is not a constructor
  • Can not be used as an arrow function inside the parameter collection constructor without arguments.
  let fun1=function(){
    console.log(arguments);
  }
  let fun=()=>{
    console.log(arguments);
  }
  fun1(100,500,800);//[100,500,800]
  fun(10,20,30);//Uncaught ReferenceError: arguments is not defined at fun
  • Arrow functions do not have a prototype.
  let funy=(a,b)=>{
    console.log(funy.prototype);
  }
  funy();//undefined






Comments

Popular posts from this blog

vue routing global guard beforeEach and afterEach

 Global routing front guard (beforeEach) This function is used the most. Its function is to perform permission-related verification before routing jumps. This function contains three parameters: to: the object of the target route that is about to enter; from: the route that the current route is leaving; next: confirm the release. It can be used to log in and register, to determine whether there is a token before logging in, and release if it exists. , if it does not exist, it will not be released. The post routing guard (afterEach), its role is to trigger after the routing jump.