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

Navicat for MySQL tutorial

First, you need to download and install Navicat f...

MySql learning day03: connection and query details between data tables

Primary Key: Keyword: primary key Features: canno...

Install zip and unzip command functions under Linux and CentOS (server)

Install zip decompression function under Linux Th...

Detailed steps to deploy lnmp under Docker

Table of contents Pull a centos image Generate ng...

How to implement input checkbox to expand the click range

XML/HTML CodeCopy content to clipboard < div s...

MySQL date processing function example analysis

This article mainly introduces the example analys...

Detailed explanation of selinux basic configuration tutorial in Linux

selinux ( Security-Enhanced Linux) is a Linux ker...

Detailed code for implementing 3D tag cloud in Vue

Preview: Code: Page Sections: <template> &l...

Implementation of Nginx Intranet Standalone Reverse Proxy

Table of contents 1 Nginx Installation 2 Configur...

Nginx local directory mapping implementation code example

Sometimes you need to access some static resource...