liveBook · Manning

New keyword

As explained in Secrets of the JavaScript Ninja, Third Edition

The new operator invokes a constructable function, creates an object for its this value, and returns the constructed object subject to explicit-return rules.

Prefix a constructable function call with `new` to create an object and pass it to the function as `this`. The function can initialize that object; unless it explicitly returns another object, the constructed object becomes the result. section 6.2.3

Ordinary functions can be constructors, but arrow and bound functions cannot. The new object also inherits from the constructor function’s `prototype`; classes use the same underlying function-and-prototype mechanism. section 6.2.3 section 9.3.2

Listing 9.5 Creating a new instance with a prototyped method
function Ninja() {} #A
 
Ninja.prototype.swingSword = () => true; #B
 
// @ts-expect-error -- Ninja has no construct signature #C
const ninja = new Ninja(); #D
console.assert( #D
  ninja.swingSword() === true, #D
  "swingSword is inherited from the prototype.", #D
); #D
console.assert( #E
  ninja instanceof Ninja, #E
  "instanceof confirms that ninja is a Ninja", #E
); #E

See a constructor-created Ninja instance inherit a method from Ninja.prototype. section 9.3.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains object creation, `this`, return behavior, and prototype inheritance without detailing lower-level runtime implementation.
Examples
Uses Ninja constructors, instance methods, and a prototype-defined method to demonstrate construction and inheritance.
What you can do after
Build it from scratch by invoking a constructor to initialize objects and inherit prototype methods.
How it connects
Connects constructors with `this`, function invocation, prototypes, and classes.

Also explained in

Compare how 4 books explain new keyword →

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.