Need several objects with the same behavior? A JavaScript class defines how to construct them and which methods they share. Unlike class-based object models in languages such as Java, JavaScript implements classes through functions and prototypes. The class keyword gives that machinery a concise form. section 9.4 section 1.1
Listing 9.6 A simple class
class Ninja {
name: string; #A
level: number; #A
constructor(name: string, level: number) { #B
this.name = name; #B
this.level = level; #B
} #B
swingSword() { #C
return true; #C
} #C
}
const ninja = new Ninja("Yoshi", 4);
console.assert(
ninja instanceof Ninja,
"The Ninja class is a constructor",
);
console.assert(
typeof Ninja.prototype.swingSword === "function",
"Instance methods belong to a prototype object",
);
console.assert(
ninja.swingSword() === true,
"Each instance inherits prototype methods",
);
console.assert(
Object.hasOwn(ninja, "name"),
"Properties assigned in the constructor belong to the instance",
);
The constructor assigns name and level to each instance. The swingSword method lives on Ninja.prototype, so instances inherit it. The assertions distinguish an instance’s own property from an inherited method and use instanceof to check the prototype chain. section 9.4.1
Keep these distinctions in mind:
- constructor runs when new creates an instance; an explicit constructor is optional. section 9.4.1
- Methods declared in the class are shared through its prototype. A static method belongs to the class itself, as with Ninja.compare(a, b), rather than to an instance. section 9.4.1
- instanceof checks whether the class’s prototype appears in an object’s prototype chain. typeof reports only a basic type, such as "object" for an instance. section 9.4.1
- extends links a child class’s prototype to its parent’s, and super refers to the parent from within the child class. section 9.5
The practical advantage is readable construction and inheritance without manually wiring prototypes. The prototype system still determines how an instance finds an inherited method. Class types are also inferred automatically in TypeScript, whereas the older constructor-function pattern may need an explicit construct type. section 9.3.2 section 9.0


























