Which scenarios in JavaScript cannot use arrow functions

Which scenarios in JavaScript cannot use arrow functions

1. Define object methods

The way to define an object method in JS is to define a property pointing to the function on the object. When the method is called, this in the method will point to the object to which the method belongs.

let obj = {
    array: [1, 2, 3],
    sum: () => {
        console.log(this === window); // true
        return this.array.reduce((result, item) => result + item);
    }
};
console.log(this === window); //true
obj.sum(); //Error: Uncaught TypeError: Cannot read property 'reduce' of undefined at Object.sum

This.array is undefined at runtime. When obj.sum is called, this in the execution context still points to window. The reason is that the arrow function binds the function context to window. This.array is equivalent to window.array, which is obviously undefined.

Modification method: Use function expressions or method abbreviations (already supported in ES6) to define methods, which ensures that this is determined by the context that contains it at runtime. The code is as follows:

let obj = {
    array: [1, 2, 3],
    sum() {
        console.log(this === window); // false
        return this.array.reduce((result, item) => result + item);
    }
};
console.log(this === window); //true
console.log(obj.sum()); //6

2. Define prototype methods

The same rule applies to prototype method definitions, using arrow functions will result in an execution context error at runtime. For example, the following code:

function Cat(name) {
    this.name = name;
}

Cat.prototype.sayCatName = () => {
    console.log(this === window); // => true
    return this.name;
};

const cat = new Cat('Tom');
console.log(cat.sayCatName()); // undefined

The problem can be solved using traditional function expressions. The code is as follows:

function Cat(name) {
    this.name = name;
}

Cat.prototype.sayCatName = function () {
    console.log(this === window); // => false
    return this.name;
}

const cat = new Cat('Tom');
console.log(cat.sayCatName()); // Tom

After sayCatName becomes a normal function, the execution context when it is called will point to the newly created cat instance.

3. Define event callback function

Arrow functions are bound to the execution context when they are declared. It is impossible to change the context dynamically. This is a disadvantage when a dynamic context is needed.

For example, in the common DOM event callback function (event listener) binding in client-side programming, when the callback function is triggered, this points to the DOM node where the event currently occurs, and the dynamic context is very useful at this time. For example, the following code attempts to use an arrow function as an event callback function.

const button = document.getElementById('myButton');
button.addEventListener('click', () => {
    console.log(this === window); // true
    this.innerHTML = 'Clicked button';
});

When the arrow function defined in the global context is executed, this will point to window. When a click event occurs, this.innerHTML is equivalent to window.innerHTML, which is meaningless.

Using function expressions, you can dynamically change this at runtime. The corrected code is:

const button = document.getElementById('myButton');
button.addEventListener('click', function () {
    console.log(this === button); // true
    this.innerHTML = 'Clicked button';
});

4. Define the constructor

This in the constructor points to the newly created object. When new Car() is executed, the context of the constructor Car is the newly created object, that is, this instanceof Car === true. Obviously, arrow functions cannot be used as constructors. In fact, JS will prohibit you from doing so and will throw an exception if you do so.

For example, the following code will report an error:

const Message = (text) => {
    this.text = text;
};
const helloMessage = new Message('Hello World!'); //Error: Throws "TypeError: Message is not a constructor"

When constructing a new Message instance, the JS engine throws an error because Message is not a constructor. The above example can be fixed by declaring the constructor using either a function expression or a function declaration.

const Message = function(text) {
    this.text = text;
};
const helloMessage = new Message('Hello World!');
console.log(helloMessage.text); // 'Hello World!'

The above is the details of which scenarios in JavaScript cannot use arrow functions. For more information about why JavaScript cannot use arrow functions, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Tips for writing better JavaScript conditionals and matching conditions (summary)
  • Detailed explanation of this pointing in JS arrow function
  • Characteristics of JavaScript arrow functions and differences from ordinary functions
  • Detailed explanation of the difference between arrow functions and normal functions in JavaScript
  • What scenarios are not suitable for JS arrow functions?
  • Introduction to JavaScript conditional access attributes and arrow functions

<<:  mysql5.7.14 decompression version installation and configuration method graphic tutorial (win10)

>>:  Detailed steps to delete environment variables in Linux

Recommend

The latest graphic tutorial of mysql 8.0.16 winx64 installation under win10

In order to download this database, it takes a lo...

Solution to mysql login warning problem

1. Introduction When we log in to MySQL, we often...

CSS layout tutorial: How to achieve vertical centering

Preface I have been summarizing my front-end know...

Implementation of React page turner (including front and back ends)

Table of contents front end According to the abov...

Beginners learn some HTML tags (3)

Beginners who are exposed to HTML learn some HTML...

Using Docker to create static website applications (multiple ways)

There are many servers that can host static websi...

Simple principles for web page layout design

This article summarizes some simple principles of...

An article to solve the echarts map carousel highlight

Table of contents Preface toDoList just do it Pre...

JS generates unique ID methods: UUID and NanoID

Table of contents 1. Why NanoID is replacing UUID...

Use of provide and inject in Vue3

1. Explanation of provide and inject Provide and ...

Solve the Linux Tensorflow2.0 installation problem

conda update conda pip install tf-nightly-gpu-2.0...

nginx automatically generates configuration files in docker container

When a company builds Docker automated deployment...

5 ways to determine whether an object is an empty object in JS

1. Convert the json object into a json string, an...