Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When 'not' to use arrow functions #8

Open
holyzfy opened this issue Oct 9, 2016 · 0 comments
Open

When 'not' to use arrow functions #8

holyzfy opened this issue Oct 9, 2016 · 0 comments

Comments

@holyzfy
Copy link
Owner

holyzfy commented Oct 9, 2016

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/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant