Detailed explanation of ES6 arrow functions and this pointing
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.
[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
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; }
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 } } // 不报错
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:
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
Analysis of the output of each line:
let f1 = obj.fun1() // obj
What is obviously done here is implicit Type binding, fun1's this points to obj
f1() // obj
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()
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
f2() is executed, prints out the modified this——window, then returns the arrow function and assigns it to f2_2f
2_2() // window
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
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
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); } } },
【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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In ES6, you can use the reverse() method of the array object to achieve array reversal. This method is used to reverse the order of the elements in the array, putting the last element first and the first element last. The syntax "array.reverse()". The reverse() method will modify the original array. If you do not want to modify it, you need to use it with the expansion operator "...", and the syntax is "[...array].reverse()".

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

Steps: 1. Convert the two arrays to set types respectively, with the syntax "newA=new Set(a);newB=new Set(b);"; 2. Use has() and filter() to find the difference set, with the syntax " new Set([...newA].filter(x =>!newB.has(x)))", the difference set elements will be included in a set collection and returned; 3. Use Array.from to convert the set into an array Type, syntax "Array.from(collection)".

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.

In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

No, require is the modular syntax of the CommonJS specification; and the modular syntax of the es6 specification is import. require is loaded at runtime, and import is loaded at compile time; require can be written anywhere in the code, import can only be written at the top of the file and cannot be used in conditional statements or function scopes; module attributes are introduced only when require is run. Therefore, the performance is relatively low. The properties of the module introduced during import compilation have slightly higher performance.

The map is ordered. The map type in ES6 is an ordered list that stores many key-value pairs. The key names and corresponding values support all data types; the equivalence of key names is determined by calling the "Objext.is()" method. Implemented, so the number 5 and the string "5" will be judged as two types, and can appear in the program as two independent keys.
