Skip to content

When 'not' to use arrow functions #8

Description

@holyzfy

Since arrow function has a short syntax, it's inviting to use it for a method definition.
You can't use an arrow function when a dynamic context is required: defining methods,
create objects with constructors, get the target from this when handling events.

Defining methods on an object

Object literal

👍

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

Object prototype

function MyCat(name) {  
  this.catName = name;
}
MyCat.prototype.sayCatName = function() {  
  console.log(this === cat); // => true
  return this.catName;
};
var cat = new MyCat('Mew');  
cat.sayCatName(); // => 'Mew'  

Callback functions with dynamic context

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

Invoking constructors

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

Too short syntax

To make it more readable, it is possible to restore the optional curly braces and
return statement from the arrow function or use a regular function

👉 https://rainsoft.io/when-not-to-use-arrow-functions-in-javascript/

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions