liveBook · Manning

Arrow function

As explained in Web Components in Action

An ECMAScript function expression written with arrow syntax that lexically captures the surrounding this value.

An arrow function is a JavaScript function expression written with =>. Its key practical benefit here is preserving the surrounding class instance as this when an event callback runs. section 2.6 section 1.1

Use an arrow function when a component callback needs to keep access to its instance:

  • Register a button listener with event => this.onBackButtonClick(event), allowing the handler to use component properties and methods. section 2.6
  • Register mouse movement with e => this.onMouseMove(e), preserving the class scope while forwarding the event to a method. section 5.3
  • Use an arrow function inside setTimeout when the delayed callback must call another method on the same component. section 5.3

Keeping a carousel callback connected to its component

this.querySelector('button.forward').addEventListener('click', event => this.onForwardButtonClick(event)); The arrow callback forwards the click event while retaining the component instance, so onForwardButtonClick can update _photoIndex and call showPhoto(). section 2.6

Listing 5.11. Adding an event listener with the fat arrow
// file: components/app/app.js

connectedCallback() {
   this.innerHTML = '<webharp-strings strings="' +
       this.getAttribute('strings') + '"></webharp-strings>';
   this.stringsElement =                                       #1
       this.querySelector('webharp-strings');
   this.addEventListener('mousemove',                          #2
       e => this.onMouseMove(e));
}

Inspect the complete event-listener example, including the arrow callback and the connected Web Harp mouse-move handler. section 5.3

How Web Components in Action covers it

How deep it goes
Defines lexical scope through working event examples, but does not develop broader function semantics or implementation internals.
Examples
Uses photo-carousel button handlers, Web Harp mouse movement, and delayed strum cleanup as concrete callback examples.
What it assumes
Assumes JavaScript classes, DOM event listeners, and component callbacks, while introducing the arrow syntax as a newer feature.
What you can do after
Apply it in event listeners and timers while retaining access to component state and methods.
How it connects
Connects arrow functions to JavaScript classes, this binding, callbacks, event listeners, timers, and Web Components.

Also explained in

Compare how 7 books explain arrow function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.