SoFunction
Updated on 2025-03-06

How to write and understand arrow functions and this in JS

Preface

JavaScript has added arrow functions to ES6 syntax. Compared with traditional functions, arrow functions are not only more concise, but also improved in this aspect. This is a strange existence in JavaScript, and many articles have different explanations of this. This article tries to clarify the relationship between functions and this in JS.

1. How to write functions in JS

1. How to write regular functions

Before ES6 syntax, functions in JS were composed of function keywords, params parameters and function bodies wrapped in curly braces. In order to distinguish it from the arrow function mentioned later, we first call such a function a regular function. Regular functions can be written in either declarative or assignment. example:

function test(name) { //Declarational writing (name)
}
test('Jerry')

let test2 = function(name) { //Assignment writing (name)
}
test2('Tom')

2. How to write arrow function

The introduction of ES6 arrow functions makes the writing of functions more concise, but certain rules must be followed in writing.

Rule 1: Arrow functions can only be written in assignment, not declarative

example:

const test = (name) => {
 (name)
}
test('Jerry')

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

example:

const test = name => {
 (name)
}
test('Jerry')

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

Rule 3: If the function body has only one sentence, you can do not add curly braces

example:

const test = name => (name) 

Rule 4: If the function body has no brackets, you can not write a return, the arrow function will help you return

example:

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

Remember: the curly braces of the function body are the same as the return keyword.

From the above examples we can see that the arrow function simplifies the parentheses and curly braces of regular functions. In addition to these simplifications, the biggest optimization of arrow functions to regular functions is this.

2. Understand this in regular functions

Before exploring the optimization of arrow functions for this, we must first 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 have not used the call method to call the function, the above definition of this may not be clear. Then we need to understand the two methods of function calls first.

1. Pure function calls

The first method is the most common, with the following examples:

function test(name) {
 (name)
 (this)
}
test('Jerry') //Calling the function

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

function test(name) {
 (name)
 (this)
}
(undefined, 'Tom')

Have you noticed the call method of the function above? The first parameter received by the call method is this, here we pass an undefined. So, according to definition, will this typed after the function is executed undefined? Neither.

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

So what we typed here is a Window object.

2. Calling of functions in objects

Let's take a look at the example directly:

const obj = {
 name: 'Jerry',
 greet: function() {
 ()
 }
}
() //The first call method(obj) //The second call method

In the example, the first calling method is just the syntax sugar of the second calling method, the second is the complete calling method, and the most powerful thing about the second method is that it can manually specify this.

Example of manually specifying this:

const obj = {
 name: 'Jerry',
 greet: function() {
 ()
 }
}
({name: 'Spike'}) //The one that is called Spike

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

3. This in the constructor

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

example:

function Test() {
  = 'Tom'
}
let p = new Test()
(typeof p) //object
() // Tom

4. Calling of functions in () and ()

This in the functions of () and () is a bit special, and this in the default is a window object.

To summarize briefly: the complete call method of a function is to use the call method, including (context, name) and (context, name). The context here is the context when the function is called, that is, this, but this can be modified through the call method; the constructor is a little special, and this directly points to the object returned after new; () and () default to this is a window object.

3. Understand this in the arrow function

There is a lot about this above. This is the first parameter passed when a function is called with the call method, and it can also be changed manually, so it is too troublesome to determine the value of this. However, the appearance of the arrow function has helped us confirm that this is a little bit.

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

As mentioned above: the value of this can be modified by the call method, and we can only determine the value of this when called. When we use the arrow function, the arrow function will bind the value of this outer layer by default, so the value of this in the arrow function is the same as this outer layer.

Example of not using arrow functions:

const obj = {
	a: function() { (this) } 
}
() //The obj object is produced

Example of using arrow functions:

const obj = {
 a: () => {
 (this)
 }
}
() //The one that is called is window

In the example of using arrow functions, because the arrow function will not use its own this by default, but will remain consistent with this on the outer layer, and the outermost layer is a window object.

2. Characteristic 2 of arrow function: This inside cannot be modified using the call method

This is also easy to understand. We have been saying before that this function can be manually specified by the call method, and in order to reduce the complexity of this, the arrow function cannot specify this with the call method.

example:

const obj = {
 a: () => {
 (this)
 }
}
('123') //The result of the print is still a window object

Because we mentioned above that this in the function in () is window by default, we can also use the arrow function to make its this consistent with this outer layer:

Example of ():

const obj = {
 a: function() {
 (this)
 (() => { 
  (this) 
 }, 1000)
 }
}
(obj) //The first this is an obj object, and the second this is still an obj object

I believe everyone understands that the function does not use the arrow function because its this is still obj, and the function in setTimeout uses the arrow function, so it will be consistent with this outer layer, which is also obj; if the function in setTimeout does not use the arrow function, then it should be a window object.

4. This function in multi-layer object nesting

Here are some doubts that the author encountered during his study. This in the arrow function is consistent with the outer layer, but if there are many layers in this outer layer, which layer is consistent with?

Directly as an example:

const obj = {
 a: function() { (this) },
 b: {
 	c: function() {(this)}
	}
}
() // The obj object is produced, which is equivalent to (obj)() //The object is printed, equivalent to ()

The above code is intuition, and then replace the corresponding function with an arrow function, and the result is as follows:

const obj = {
 a: function() { (this) },
 b: {
 	c: () => {(this)}
	}
}
() //The obj is not used to type the arrow function() //The window object is printed!  !

The obj object is played after the call, and the window object is played after the call, not obj, which means that this is consistent with the outermost layer in the arrow function in the multi-layer object nesting.

The above content is the knowledge points sorted out by the author’s learning arrow function. If there are any errors, please criticize and correct them! This is the third article I wrote on the Nuggets, thanks for reading!

References to this article:What is the value of this? Explain it clearly at once

Summarize

This is the article about the writing and understanding of arrow functions and this in JS. This is all about this. For more related JS arrow functions and this content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!