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

Comments:

  1. Looks scala-like

  2. Hm, couldn’t you just have written

    this.addEventListener(.., function (event) { … });

    ?

  3. @Šime sure, but the function() syntax is longer and doesn’t automatically get the binding mechanism. One of the nice benefits is that you don’t accidentally use the wrong/global this from inside the callback. Typically if you are adding a callback from a method, you probably expect this to refer to the same object of the method you’re in.

  4. I wonder why are arrow functions so horribly slow http://jsperf.com/arrow-functions, is it because of the way they are defined in spec or they just didn’t have enough time yet to be optimized?
    Right now they are even slower than bind.

  5. It’s partly a matter of both. Arrow functions are “bound functions”, which in SpiderMonkey right now means you invoke the bound function, then that invokes a target function with the original |this| (and, for bound functions created by Function.prototype.bind, any leading arguments specified when the function was bound). This extra invocation takes a little time, and any arguments you pass in have to be passed in to the bound function, then copied and passed into the target function. So there’s some overhead still.

    SpiderMonkey will eventually optimize calling bound functions so that these costs are reduced — in the case of arrow functions, possibly so they even disappear, as there’s recognizable syntax permitting full elimination of binding costs. But we try to concentrate on the things the web’s using now when deciding what to optimize, so it’s unclear exactly when we’ll get to bound function performance.


Add a Comment