Writing and understanding of arrow function in JS and this

  • 2021-10-24 18:44:45
  • OfStack

Preface to the catalogue 1. Writing of functions in JS
1. How to write regular functions
2. How to write the arrow function
2. Understand this in regular functions
2. Calling a function in an object
3. this in the constructor
4. Calls to functions in window. setTimeout () and window. setInterval ()
3. Understand this in the arrow function
1. Feature 1 of the arrow function: Default binding outer layer this
2. Feature of arrow function 2: You can't modify this in call method
4. this of functions in multi-layer object nesting
Summarize

Preface

JavaScript adds arrow function in ES6 syntax. Compared with traditional functions, arrow function is not only simpler, but also improved in this. this is a strange existence in JavaScript, and many articles have different explanations for this. This article tries to clarify the relationship between functions in JS and this.

1. How to write functions in JS

1. How to write regular functions

Prior to the ES6 syntax, functions in JS consisted of function keywords, params parameters, and a function body wrapped in curly braces. In order to distinguish it from the arrow function mentioned later, we first call such a function a regular function, which can be written either declaratively or by assignment. Examples:


function test(name) { // Declarative writing 
 console.log(name)
}
test('Jerry')

let test2 = function(name) { // Writing of assignment formula 
 console.log(name)
}
test2('Tom')

2. How to write the arrow function

The introduction of ES6 arrow function makes the writing of the function more concise, but the writing should follow the rules of 1.

Rule 1: Arrow functions can only be written by assignment, not by declaration

Examples:


const test = (name) => {
 console.log(name)
}
test('Jerry')

Rule 2: If there is only one parameter, you can not add parentheses. If there are no parameters or more than one parameter, you need to add parentheses

Examples:


const test = name => {
 console.log(name)
}
test('Jerry')

const test2 = (name1, name2) => {
 console.log(name1 + ' and ' + name2)
}
test2('Tom', 'Jerry')

Rule 3: If the function body has only one sentence, it can be without curly braces

Examples:


const test = name => console.log(name) 

Rule 4: If there are no parentheses in the function body, you can not write return, and the arrow function will help you return

Examples:


const add = (p1, p2) => p1 + p2
add(10, 25)

Remember: The curly braces of the function body are with the return keyword.

From the above example, we can see that the arrow function simplifies the parentheses and curly braces of conventional functions. In addition to these simplifications, the biggest optimization of arrow functions over conventional functions lies in this.

2. Understand this in regular functions

Before exploring the optimization of the arrow function for this, we need to understand what this is and how it is used. this is the first parameter passed when calling a function using the call method. It can be modified when the function is called. When the function is not called, the value of this cannot be determined.

If you haven't used the call method to call a function, the above definition of this may not be clear. Then we need to understand two methods of function calling first.

1. Pure function calls

The first method is the most common, and an example is as follows:


function test(name) {
 console.log(name)
 console.log(this)
}
test('Jerry') // Call function 

We use this method most, but this function call method is only a shorthand, and its complete writing is as follows:


function test(name) {
 console.log(name)
 console.log(this)
}
test.call(undefined, 'Tom')

Notice the call method of the function called above? The first parameter that the call method receives is this, where we pass an undefined. So, by definition, will the this typed after the function is executed be undefined? Nor is it.

If your context is null or undefined, then the window object is the default context (the default context is undefined in strict mode).

So the this we typed here is the Window object.

2. Calling a function in an object

Look directly at the example:


const obj = {
 name: 'Jerry',
 greet: function() {
 console.log(this.name)
 }
}
obj.greet() // No. 1 1 Kinds of calling methods 
obj.greet.call(obj) // No. 1 2 Kinds of calling methods 

In the example, the first call method is only the syntax sugar of the second call method, and the second call method is the complete call method, and the great thing about the second method is that it can specify this manually.

An example of manually specifying this:


const obj = {
 name: 'Jerry',
 greet: function() {
 console.log(this.name)
 }
}
obj.greet.call({name: 'Spike'}) // What is typed is  Spike

From the above example we can see that when the greet function is executed, this has been modified by us.

3. this in the constructor

this in the constructor is slightly special. Each constructor will return an object after new, which is this, that is, context context.

Examples:


function Test() {
 this.name = 'Tom'
}
let p = new Test()
console.log(typeof p) //object
console.log(p.name) // Tom

4. Calls to functions in window. setTimeout () and window. setInterval ()

There is something special about this in the functions of window. setTimeout () and window. setInterval (), where this is an window object by default.

Brief summary 1: The complete calling method of the function is to use call method, including test. call (context, name) and obj. greet. call (context, name). context here is the context when calling the function, that is, this, but this this can be modified by call method; The constructor is slightly special in that its this points directly to the object returned after new; window. setTimeout () and window. setInterval () default that this is an window object.

3. Understand this in the arrow function

Much has been said about this, which is the first parameter passed when a function is called with the call method, and it can be changed manually, making it too much trouble to determine the value of this. However, the appearance of the arrow function helps us to determine this.

1. Feature 1 of the arrow function: Default binding outer layer this

As mentioned above, the value of this can be modified with the call method, and we can only determine the value of this at the time of call. When we use the arrow function, the arrow function will help us bind the value of the outer layer this by default, so the value of this in the arrow function is the same as that of the outer layer this.

Example of not using arrow function:


const test = (name) => {
 console.log(name)
}
test('Jerry')
0

Examples of using arrow functions:


const test = (name) => {
 console.log(name)
}
test('Jerry')
1

In the example of using the arrow function, because the arrow function will not use its own this by default, but will keep 1 with the outer this, and the outermost this is the window object.

2. Feature of arrow function 2: this cannot be modified by call method

This is also easy to understand. As we said in the previous 1, the this of the function can be specified manually by call method, but in order to reduce the complexity of this, the arrow function cannot specify this by call method.

Examples:


const test = (name) => {
 console.log(name)
}
test('Jerry')
2

Because we mentioned above that this in the function of window. setTimeout () defaults to window, we can also keep its this and outer this 1 through the arrow function:

Examples of window. setTimeout ():


const obj = {
 a: function() {
 console.log(this)
 window.setTimeout(() => { 
  console.log(this) 
 }, 1000)
 }
}
obj.a.call(obj) // No. 1 1 A this Yes obj Object, the 2 A this Or obj Object 

As you must understand, the function obj. a does not use the arrow function, because its this is still obj, and the function in setTimeout uses the arrow function, so it will keep 1 with the outer this, which is also obj;; If the function in setTimeout does not use the arrow function, it should type the window object.

4. this for functions in multi-level object nesting

Here is one doubt that the author encountered when studying. this in the arrow function is 1 with the outer layer, but if this outer layer has multiple layers, which layer is it 1 with?

Direct example:


const test = (name) => {
 console.log(name)
}
test('Jerry')
4

The above code is intuitive. Next, replace the corresponding function of obj. b. c with an arrow function, and the result is as follows:


const test = (name) => {
 console.log(name)
}
test('Jerry')
5

After calling obj. a, obj object is typed, while after calling obj. b. c, window object is typed instead of obj, which means that this in the arrow function in the multi-layer object nesting keeps 1 with the outermost layer.

The above content is the author's knowledge points combed out in the arrow function. If there are mistakes, please criticize and correct them! This is the third article I wrote on the Nuggets. Thanks for reading!

Reference to this article: What is the value of this? Make it clear once

Summarize


Related articles: