Doubt in the declaration between expression arrow and expression of function of an event

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 not, what's the difference?

Thank you!

    
asked by anonymous 03.11.2016 / 13:19

2 answers

2

There are differences in the way you work, beyond the look.

() => {} is an arrow function and always runs in the context that has been called. It does not accept .bind , .call , .apply or other ways to enforce an execution context.

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

Notice 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, this behaves quite differently.

    
03.11.2016 / 17:11
3

Arrow Function belongs to the ECMAScript 2015 , has a syntax more short and binds the this value lexically.

  

An expression arrow function has a shorter syntax when   compared to function expressions and links the   value of this in a lexical way. 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 arrow functions every function defined its own value this . This behavior is annoying with an object-oriented programming style.

In this documentation you can find more examples between the two types .

    
03.11.2016 / 13:55