Several situations in which you should avoid using arrow functions

⭐️ more front-end technology and knowledge, search subscription number JS bacteria subscription

Avoid using it when defining object methods

The arrow function is popular because of its concise syntax. However, the absence of this can lead to unexpected situations in some cases. 😯

For example, defining a method on an object:

It seems perfect that calling this method will get the object’s food property as expected

But if you change it to an arrow function:

Since the arrow function does not have this itself, it automatically inherits this from the outer layer, resulting in errors in printed variables. This bug is a bit 🍤

Therefore, do not use arrow functions in object methods

Avoid using it on Prototype

Remember not to use arrow functions when defining prototype methods because there is no this to point to

Avoid using arguments on needs

Since the arrow function has no arguments, so if the outer layer is another function, then arguments is for that outer function

Of course, you can use the REST operator to get the corresponding parameters

Avoid using callback functions in dynamic context

If you need your context to be mutable, dynamic, then don’t use arrow functions

For example, in a page, we need to add an event handler for each p element, then:

document.querySelectorAll('p').forEach(elem= > {
    elem.addEventListener('click', () = > {console.log(this.innerText.length) // ❌ This refers to the window, so an error is reported})})Copy the code

To access the expected this correctly, change to a normal function:

document.querySelectorAll('p').forEach(elem= > {
    elem.addEventListener('click'.function() {
        console.log(this.innerText.length) // ✅ this points to elem})})Copy the code

Avoid using it when you need a caller

As caller is no longer a standard for recommendation, we should avoid using caller at any time

In other cases, especially map Reduce forEach where there is no complex logic, using the arrow function can add to the reading experience, which would be great 👏

that’s all

Please pay attention to my subscription number, push technical articles about JS irregularly, only talk about technology not gossip 😊