Doubt in the statement between Arrow expression and function expression of an event

Asked

Viewed 169 times

8

I have the following code snippet:

self.addEventListener('push', event => {"code here"});

My question is... this writing format is equal to:

self.addEventListener('push', function(event) {"code here"});

And if it’s not, what’s the difference?

Thank you very much!

2 answers

3

Arrow Function belongs to the Ecmascript 2015, has a shorter syntax and binds the value this lexically.

An Arrow Function expression has a shorter syntax when compared to function expressions (Function Expressions) and links the this value lexically. Arrow functions are always anonymous.

Example:

var a = [
  "Hidrogenio",
  "Helio",
  "Litio",
  "Berilio"
];

var a2 = a.map(function(s){ return s.length });

var a3 = a.map( s => s.length );

Note for the absence of Return in the second function.

Before the Arrow functions every function defined its own value this. This behavior is bothersome with an object-oriented programming style.

In that documentation it is possible to find more examples between the two types.

2


There are differences in the way it works, beyond the appearance.

() => {} is an arrow function (Arrow Function) and always runs in the context it was called. It does not accept .bind, .call, .apply or other ways to impose an execution context.

In the case of your code, an event headphone, the difference is great because the this is usually the element that received the .addEventListener and that’s the way to distinguish from event.target that is lost with event => {}.

Look at this example (jsFiddle):

var div = document.querySelector('div');
var info = document.querySelector('#info');

div.addEventListener('click', function(e){
	info.innerHTML += ['legacy', this, e.target.tagName, '<br>'].join(' ');
});
div.addEventListener('click', e => {
	info.innerHTML += ['arrow', this, e.target.tagName, '<br>'].join(' ');
});
<div>
    <button type="button">Clica-me!</button>
</div>
<p id="info"></p>

In these cases the this behaves quite differently.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.