28 March 2013 - 6:57No self for new fancy => arrow functions!

Thanks Paul for letting people know how to define JavaScript functions, the ES6 way (in Firefox 22). I’m now busy converting my anonymous functions, e.g., function(x) x*x, to the new syntax: x => x*x.

But one thing caught my eye in the spec he linked, harmony:arrow_function_syntax:

// ''=>'' has only lexical ''this'', no dynamic ''this''

This means you no longer need to bind or do the self = this dance. Both patterns are common for setting up callbacks in JavaScript.

So if your code in a method of an object used to look like either of..

addEventListener(.., function(event) {
  .. this.value ..;
}.bind(this));

or

let self = this;
addEventListener(.., function(event) {
  .. self.value ..;
});

Your code can now look like this!

addEventListener(.., event => {
  .. this.value ..;
});

Exciting stuff! 🙂

5 Comments | Tags: Development, Mozilla