liveBook · Manning

Method

As explained in Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond

A function associated with an object or class that is invoked through that object or class.

Suppose each object produced by a prisoner factory must answer the same question: will it snitch? A method gives the object a function to answer it. Calling `prisoner.snitch()` returns `true` or `false`, so the simulator can use each new prisoner through the same interface. section 19.1

Methods can be written on objects or in a class body. The syntax looks similar, but the surrounding rules differ:

  • An object yielded by a generator can contain `snitch() { return true }`. Each yield provides a new object with that method. section 19.1
  • A class can declare `fetch() { /* fetch records */ }`. Class methods can accept parameters and use `this` to refer to the instance. section 27.1
  • Do not write `fetch: function() {}` in a class body or put commas between class methods. Those object-literal conventions cause syntax errors there. section 27.1

A method passed as a callback

Imagine `fetch()` calls `ajax(this.url, this.handleNewRecords)`. The ajax library later invokes the callback, but `handleNewRecords` is not automatically bound to the data-store instance. Its `this.records = records` therefore will not store the records on that instance. Instead, pass `records => this.handleNewRecords(records)`: the arrow function makes the call through the instance when the records arrive. section 27.4

Listing 27.2. Using unbound methods as callbacks
class DataStore { fetch() { ajax(this.url, this.handleNewRecords) 1 } handleNewRecords(records) { this.records = records 2 } }

Trace the two marked lines: first the method is handed to `ajax` as a callback; later its use of `this` no longer points to the instance. section 27.4

How Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond covers it

How deep it goes
Shows object and class method syntax, then works through an unbound callback and an arrow-function fix.
Examples
Uses a generated prisoner's `snitch()` method, a data-store `fetch()` method, and an ajax callback that loses instance access.
What it assumes
Assumes familiarity with object-method shorthand and explains how class declarations differ from object literals.
What you can do after
Diagnose/debug with it when an ajax callback loses instance access, then preserve that access with an arrow-function wrapper.
How it connects
Connects methods to object interfaces, generators, class declarations, callbacks, and arrow functions.

Also explained in

Compare how 20 books explain method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming with JavaScript Next: New features of ECMAScript 2015, 2016, and beyond. The section links point to the parts of the book it draws on.