liveBook · Manning

New keyword

As explained in The Joy of JavaScript

The JavaScript operator keyword that creates a new object instance by invoking a constructor function or class.

The new keyword creates an object by instantiating a constructor function and linking the result to that function’s prototype. This link enables shared methods instead of copying them onto every instance. section 2.2.2

Constructor calls demonstrate two important behaviors:

  • new HashTransaction(...) creates an instance whose constructor and prototype links support shared behavior. section 2.2.2
  • Calling HashTransaction(...) without new can fail when the constructor assigns through an unavailable this value; new.target can redirect such calls. section 2.2.2
  • Class constructors likewise require new; invoking one directly raises a TypeError. section 2.2.2

Shared prototype methods

After HashTransaction.prototype.calculateHash is defined, tx1.calculateHash === tx2.calculateHash evaluates to true, showing that instances share the same method. section 2.2.2

Figure 2.3 The instantiation of tx per listing 2.6, together with a complete picture of all prototype links and constructor references. In JavaScript, constructor functions automatically obtain a reference to the prototype property upon instantiation with the new keyword. The navigation annotated with [[Prototype]] represents the internal __proto__ link between objects.

Trace an instantiated transaction through its constructor reference, prototype property, and internal [[Prototype]] links. section 2.2.2

How The Joy of JavaScript covers it

How deep it goes
Explains prototype links, constructor references, method sharing, and safeguards against improper calls.
Examples
Uses Transaction and HashTransaction instances, shared methods, TypeErrors, new.target, and Object.create prototype configuration.
What you can do after
Apply it via constructor functions to create instances with shared prototype methods and safer invocation behavior.
How it connects
Connects constructors with prototypes, prototype chains, inheritance, and classes.

Also explained in

Compare how 2 books explain new keyword →

Related concepts

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