JavaScript Class Declarations and Instance Methods
Quick answer
Class syntax declares a constructor and methods using JavaScript’s prototype-based object model. Class constructors require construction rather than ordinary invocation.
How it works
Use class Name { constructor(...) { ... } method() { ... } }. Public instance methods are installed on Name.prototype and shared by instances. Constructor code establishes instance state. Class body code is strict. Class declarations have lexical initialization rules; a class expression can also produce a class value.
class Box { constructor(n) { this.n = n; } double() { return this.n * 2; } }const a = new Box(3); const b = new Box(5); console.log(a.double(),b.double(),a.double===b.double);Expected output in Node.js:
6 10 trueTwo instances share the method but have separate own n values.
const Label = class { text() { return "ready"; } };const x = new Label(); console.log(x.text(),Object.hasOwn(x,"text"));Expected output in Node.js:
ready falseThe method belongs to the class prototype.
Common mistakes
Class syntax does not create a separate inheritance system outside the prototype model.
Practice
Create a rectangle class with two instances and verify their method identity.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Class Declarations and Instance Methods — Knowledge Check
Apply the taught concept and predict the output.
Where are ordinary public instance methods installed by class syntax?
Can an ordinary class constructor be called without new?
What strictness applies to code in a class body?
What is the exact console output in JavaScript Class Declarations and Instance Methods example 1?
class Box { constructor(n) { this.n = n; } double() { return this.n * 2; } }const a = new Box(3); const b = new Box(5); console.log(a.double(),b.double(),a.double===b.double);What is the exact console output in JavaScript Class Declarations and Instance Methods example 2?
const Label = class { text() { return "ready"; } };const x = new Label(); console.log(x.text(),Object.hasOwn(x,"text"));