liveBook · Manning

Call

As explained in Secrets of the JavaScript Ninja, Third Edition

A function invocation is an operation that calls a function and supplies zero or more arguments to it.

A function call runs a function and may supply values called arguments. The variables named in the function definition are parameters. JavaScript assigns arguments to parameters in order; supplying more arguments than named parameters does not itself raise an error. section 5.4

Arguments are values at the call site

function practice(person, tool) { return `${person}: ${tool}`; } practice("Yoshi", "sword", "katana"); Here, person receives "Yoshi" and tool receives "sword". The third argument has no matching parameter name. section 5.4

A call need not start with a declared function name. A variable holding a function can be called, and a function expression can be called immediately: `(function (value) { return value; })("hello")`. section 5.1.1

For an ordinary function, the form of the call also affects its implicit `this` value:

  • `work()` calls it as a standalone function; in strict mode, `this` is undefined. section 6.4
  • `object.work()` calls it as a method; `this` is usually the object used for the call. section 6.4
  • `new Worker()` calls it as a constructor; `this` is the newly constructed object. section 6.4
  • `work.call(object, value)` or `work.apply(object, [value])` supplies `this` explicitly. section 6.2 section 6.4

A copied method can lose its context

class Worker { train() { return this; } } const worker = new Worker(); worker.train() === worker; // true const train = worker.train; train() === worker; // false in strict mode Copying the function does not preserve the method call. In strict mode, the standalone call receives undefined as `this`; a method that uses `this` to access instance data can fail. An arrow function instead retains `this` from its surrounding context, while `bind` can fix an ordinary function's context. section 6.1 section 6.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Works through argument assignment and four invocation forms, including their effects on `this`.
Examples
Illustrates positional arguments, immediate function-expression calls, and a class method that fails after extraction.
What it assumes
Assumes basic familiarity with JavaScript functions and objects while defining the argument–parameter distinction and introducing invocation-dependent `this`.
What you can do after
Diagnose/debug with it when a method loses its expected `this`, and choose a call form that supplies the intended context.
How it connects
Connects function calls to parameters, `this`, methods, constructors, arrow functions, and `bind`.

Also explained in

Compare how 8 books explain call →

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.