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

Mobile terminal adaptation makes px automatically converted to rem

Install postcss-pxtorem first: npm install postcs...

Understanding Vuex in one article

Table of contents Overview Vuex four major object...

W3C Tutorial (7): W3C XSL Activities

A style sheet describes how a document should be ...

Detailed explanation of Grid layout and Flex layout of display in CSS3

Gird layout has some similarities with Flex layou...

The principle and application of MySQL connection query

Overview One of the most powerful features of MyS...

Pitfall notes of vuex and pinia in vue3

Table of contents introduce Installation and Usag...

Analysis of the principles and usage of Docker container data volumes

What is a container data volume If the data is in...

Tutorial on installing MySQL under Linux

Table of contents 1. Delete the old version 2. Ch...

MySQL chooses the right storage engine

When it comes to databases, one of the most frequ...