Home > Web Front-end > Front-end Q&A > Detailed explanation of ES6 arrow functions and this pointing

Detailed explanation of ES6 arrow functions and this pointing

WBOY
Release: 2022-08-08 10:43:02
forward
1619 people have browsed it

This article brings you relevant knowledge about javascript, which mainly introduces arrow functions and related issues pointed by this. This in ordinary functions represents the object when this function is called. The arrow function does not have its own this. The this inside the arrow function will inherit from the external this. Let’s take a look at it. I hope it will be helpful to everyone.

Detailed explanation of ES6 arrow functions and this pointing

[Related recommendations: javascript video tutorial, web front-end

1. Arrow Function

Use arrows => Define function

 var fn = function(num){
    return num;}var fn1 = (num)=>num;var fn3 = ()=>1;var  fn4 = (num1,num2,num3)=>num
Copy after login

If there are multiple statements in the code block part of the arrow function, use curly brackets to surround them, and use return to return .

        var func = (a,b)=>{
            return a+b;
        }
Copy after login

Since curly braces {} are interpreted as code blocks, if the arrow function directly returns an object, curly braces must be added outside the object, otherwise an error will be reported.

var func = (a,b)=>{name:a,age:b} //报错var func4 = (a,b)=>{
    return {
      name: a,
      age :b   } } // 不报错
Copy after login

The arrow function also has a more important role: to solve the pointing problem of this.

2.this points to

Let’s first talk about this in ordinary functions. This in ordinary functions represents the object when this function is called. The arrow function does not have its own this. The this inside the arrow function will inherit from the external this. Or it would be more intuitive to explain it using the concept of code

block: this in the arrow function is this in the outer code block. Give an example:

Detailed explanation of ES6 arrow functions and this pointing

Detailed explanation of ES6 arrow functions and this pointing

The arrow function is a new feature in ES6. It does not have its own this, and its this points to the outer layer. Code base inheritance.

There are a few points to note when using arrow functions:

  • Arrow functions cannot be used as constructors, and an error will be thrown if they are used
  • The arguments parameter cannot be used. If you want to use it, use rest
  • The yield command cannot be used, so the arrow function cannot be used as a Generator function
  • Because it does not have its own this, there is no You can't change this pointer through bind, call, and apply
  • But this does not mean that the this pointer of the arrow function is static. We can control it by changing the this pointer of its outer code base
  • The this of the arrow function is inherited from the outer code base, so the this of the arrow function is bound when it is defined, while for ordinary functions, it is determined when calling that this points directly to the
  • literal object. The this of the defined arrow function does not bind the object, but looks for a layer outside. The simplest case is to bind it to window

PS: In the actual development environment, React can use the arrow function to solve the problem. A classic question that I won’t go into details here.

Give an example to see the actual situation of the arrow function:

const obj = {
  fun1: function () {
    console.log(this);
    return () => {
      console.log(this);
    }
  },
  fun2: function () {
    return function () {
      console.log(this);
      return () => {
        console.log(this);
      }
    }
  },
  fun3: () => {
    console.log(this);
  }
}

let f1 = obj.fun1(); // obj
f1() // obj

let f2 = obj.fun2();
let f2_2 = f2(); // window
f2_2() // window

obj.fun3(); // window
Copy after login

Analysis of the output of each line:

let f1 = obj.fun1() // obj
Copy after login

What is obviously done here is implicit Type binding, fun1's this points to obj

f1() // obj
Copy after login

The arrow function returned from the previous line is executed here. We analyze that this of the previous layer of the code library points to obj, so it is inherited directly, and the arrow function this points to

objlet f2 =obj.fun2()
Copy after login

The first layer of fun2 did not print the code when it was executed, but returned a function and assigned it to f2, and a binding loss occurred here, and this pointed from the original obj to window (an assignment occurred)

let f2_2 = f2() // window
Copy after login

f2() is executed, prints out the modified this——window, then returns the arrow function and assigns it to f2_2f

2_2() // window
Copy after login

executes and prints out the window, the outer layer just now Doesn't the this of the code point to window, so window is inherited here as this

obj.fun3() // window
Copy after login

The arrow function directly defined in the literal cannot inherit the this of the object. Instead, look one layer outside and you will find it. window, because literal objects cannot form their own scope, but constructors can.

So how do we control the this point of the arrow function:

The answer is to modify the this point of the outer code base, and just change the direction of this before the arrow function is defined.

Based on the above code:

let fun4 = f2.bind(obj)() // obj
fun4() // obj
Copy after login

We found that what was modified was the this point of the second-layer method, and the arrow function was also inherited.

  fun2: function () {
    return function () { // 我们修改的是这里的this
      console.log(this);
      return () => { // 然后这里定义的时候就继承啦
        console.log(this);
      }
    }
  },
Copy after login

【Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of Detailed explanation of ES6 arrow functions and this pointing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
es6
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template