Do you really know arrow functions

Keywords: Javascript Front-end ECMAScript

highlight: a11y-dark
theme: channing-cyan

Arrow function

🙊 I believe everyone has used the arrow function. People who can use it have tried it repeatedly. They are afraid that if they use it wrong, they may choose not to use it. It is a matter of multiple codes and a few lines of words. But people who have used it say it's really cool. Then this article will find out how to play the arrow function.

Use of arrow function

Let's have a deeper understanding of using arrow functions according to the comparison between ordinary functions and arrow functions

1. Grammatical format

Our common function syntax format is like this

function(){Function body content}

However, our arrow function is like this, isn't it very concise

(parameter)=>{Function body content}

🏀 For example, we traverse the array and modify the array

var hobby=["having dinner","sleep","play a ball"]
    var arr = hobby.map(function(item){ //Ordinary function implementation
        return "Zhang San likes it"+item;
    })
    var brr =hobby.map((item)=>{return "Li Si likes it"+item}); //Arrow function implementation
    console.log(arr)
    console.log(brr)

🏀 If you want to return an object and change the writing method, the wrong writing method will be regarded as the content of the function body

 var obj1 = ()=>{name:"Romantic code farmer";age:20} //Wrong writing
 var obj = ()=>({name:"Romantic code farmer",age:20}) //Correct writing
  console.log(obj1(),"Wrong writing")
  console.log(obj(),"Correct writing")

To summarize:

  1. If there is only one parameter, you can omit (). If there is only one statement in the function body, you can omit {} and return. The above example can be omitted as var BRR = hobby.map (item = > "Li Si likes" + item);
  2. As an anonymous function, the arrow function cannot be named

2. The direction of this

Arrow functions do not have their own execution context. So there's no this,arguments,

this of the arrow function points to the parent of the object it is in

🏀 Give me an example

    var a = {
        name: "May you go through thousands of sails",
        init: function () {
            console.log(this)
            console.log(this.name)
        }
    }
    var b = {
        name: "Finally get what you want",
        init: ()=> {
            console.log(this)
            console.log(this.name)
        }
    }
    a.init()
    b.init()

It can be seen that the ordinary function this points to its own object, while the arrow function this points to the window in the outer layer. Because the window has no name field, it has no output.

The arrow function changes this from "dynamic" to "static". The essence is that there is no internal this point and inherits the parent object's this point

This of the arrow function points to this in the external scope when it is defined, and this of the ordinary function points to the confirmation according to the context when it is called

3. Cannot be used as constructor

As an anonymous function, the arrow function does not have a prototype or its own this point, so the new constructor cannot be used

For example:

    function mao(name,age){ //Ordinary function
        this.name=name,
        this.age=age
    }
    var fn = (name,age) => ({ //Arrow function
        name:name,
        age:age
    })
    var b = new mao("Romantic code farmer",100) //Ordinary function
    console.log(b)
    var a = new fn("Zhang San",200) // Arrow function
    console.log(a)

analysis:

💠 First, we need to know what the procedure of constructor new is

  1. Create an empty object {};
  2. Point the prototype chain of the object to be instantiated to the object prototype.
  3. Bind the object to the point of this
  4. Returns the object.

Since the arrow function does not have a prototype and does not have its own this point, arguments cannot be used.

🏀 Post a handwritten new constructor here. Let's explore the constructor in depth in the future

function mao(name,age){
        this.name=name;
        this.age=age;
   }
//Handwritten new
function _new(fn, ...args){ // ... args is the ES6 expander, or arguments can be used
    //First create an empty Object with Object
    let obj=new Object();
    //The new object is prototype d
    obj.__proto__=fn.prototype;
    //The new object is bound to this of the function call
    let res=fn.call(obj,...args);
    //Judge whether the return value of the function is null or undefined, return obj, otherwise return res
    return res instanceof Object?res:obj;
}
var a= _new(mao,"Romantic until death",20)
console.log(a)

💠 Write at the end

🙊 If the above is wrong, you are welcome to point it out. Thank you very much.

💌 May you go through thousands of sails and finally get what you want 💌

A romantic universe, but also cherish the daily code farmers in the world

Posted by madmindz on Tue, 30 Nov 2021 15:19:53 -0800