liveBook · Manning

Method

As explained in Secrets of the JavaScript Ninja, Third Edition

A function associated with an object or class and typically invoked through that association.

A method is a function associated with an object and invoked through that object. In JavaScript, the way a function is invoked determines its `this` value: `ninja.skulk()` invokes `skulk` as a method, tying the call to `ninja`. This differs from languages where `this` is determined only by where a method is defined. section 6.2 section 6.1

function skulk(name) {}
function Ninja(name) {}
 
skulk("Hattori"); #A
(function (who) { #A
  return who; #A
})("Hattori"); #A
 
const ninja = {
  skulk: function () {},
};
 
ninja.skulk("Hattori"); #B
 
ninja = new Ninja("Hattori"); #C
 
skulk.call(ninja, "Hattori"); #D
 
skulk.apply(ninja, ["Hattori"]); #E

Compare method invocation with standalone calls, constructor calls, and calls using `call` or `apply`. section 6.2

A method can be assigned to a variable, but calling it separately may lose its object context. The same trap occurs when passing a method as a callback: the receiving function gets the function, not its original object association. Function binding and arrow functions are tools for addressing this unbound-method problem. section 6.1 section 6.3

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains method invocation and its effect on `this`, while deferring getter and setter internals.
Examples
Uses `ninja.skulk()`, class methods, and a DOM click-handler callback to demonstrate method context.
What you can do after
Diagnose unbound-method failures by tracing how a method is invoked, including when it is passed as a callback.
How it connects
Links methods to `this`, function invocation, constructors, `call`, `apply`, getters, setters, and callbacks.

Also explained in

Compare how 25 books explain method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.