Thursday 20 October 2016

Avoiding anonymous JavaScript functions


Anonymous functions, the art of the callback. I’m going to propose that you never write a callback again using an anonymous function, and I’ll sell you the idea now. Firstly, what is an anonymous function? Something like this: document.querySelector(‘.menu’).addEventListener(‘click’, function (event) {
// we’re inside the anon callback, btw…
if (!this.classList.contains(‘active’)) {
this.classList.add(‘active’);
}
event.preventDefault();
}, false);
Here’s a few reasons why you should stop doing this… anonymous functions:
Are more difficult to debug
Cannot be reused
Cannot be tested easily
Do not describe the role of the function
Make code lack structure
Create messier/unclear code
Documentation will suffer (things like jsDoc)
Let’s investigate. Based on our above code example, I can see a click event was bound and it executes a function which adds a class. But what for? So far (apart from an educated guess), I can only assume that it toggles a tab or a menu. So why are we so reliant on using anonymous functions instead of helping ourselves write better code?
“But what does this code do?”. At this point, you remove your headphones,
Source: https://managewp.org/articles/13678/avoiding-anonymous-javascript-functions




source https://williechiu40.wordpress.com/2016/10/21/avoiding-anonymous-javascript-functions/

No comments:

Post a Comment