JavaScript Classes Explained: Private Fields, Static Members and Extends
JavaScript classes give you a clean way to bundle data and behaviour. Learn constructors, methods, #private fields, getters, static members, extends and super, plus the errors you will hit, with output from tested Node.js code.
- JavaScript classes are cleaner syntax over prototypes.
typeofa class is still"function". - Fields that start with
#are truly private. Code outside the class cannot read them, and naming one there is a syntax error. staticmembers belong to the class itself, andextendsplussuper()handle inheritance.- Classes must be called with
new, are not hoisted for use, and methods losethiswhen passed around unless you bind them or use arrow fields.
Before 2015, building objects in JavaScript meant constructor functions and editing prototype by hand. It worked, but it was easy to get wrong and hard to read. JavaScript classes fixed the readability, and later additions such as private fields and static blocks made them a real tool for organising code.
In this guide we build one small banking example step by step, then cover inheritance, how classes relate to prototypes, and the mistakes that cause bugs. We ran every snippet with Node.js 24.22.1 as an ES module, so strict mode was on.
What is a class in JavaScript?
A class is a blueprint for objects. It describes the data each object holds and the methods that work on that data. You create objects, called instances, with new. Classes are a good fit when you will create many objects with the same shape and behaviour, such as users, orders, page objects in a test suite or UI components.
If you are new to the language, our JavaScript tutorial for beginners covers objects and functions first.
A first class: fields, constructor and methods
class Account {
#balance = 0;
static count = 0;
constructor(owner, opening = 0) {
this.owner = owner;
this.#balance = opening;
Account.count++;
}
deposit(amount) {
if (amount <= 0) throw new RangeError("amount must be positive");
this.#balance += amount;
return this;
}
get balance() { return this.#balance; }
static compare(a, b) { return a.#balance - b.#balance; }
toString() { return `${this.owner}: ${this.#balance}`; }
}
const a = new Account("Asha", 100).deposit(50);
console.log(String(a)); // Asha: 150
The parts:
- Field declarations such as
#balance = 0set up each instance before the constructor body runs. - The constructor runs once per
newcall and receives the arguments. - Methods such as
deposit()live on the prototype and are shared by every instance. Returningthislets you chain calls. - Getters such as
balancelook like properties to callers.
Private fields with #
A field whose name starts with # is private to the class body. It is not a naming convention like the old underscore prefix. The engine enforces it:
console.log(a.balance, a["#balance"], Object.keys(a));
// 150 undefined [ 'owner' ]
The getter returns 150. The bracket lookup finds nothing, because "#balance" as a string is just an ordinary missing property. Object.keys() lists only owner. And if code outside the class writes #balance directly, the file does not even load. Node stopped our script before running it:
SyntaxError: Private field '#balance' must be declared in an enclosing class
Notice that the static method compare(a, b) can read a.#balance of another instance. Privacy is per class, not per object, so any code inside the class body can see the private fields of any instance of that class. You can also write private methods, such as #validate(), the same way.
Getters and setters
A getter computes a value on read, and a setter runs on write. Our class has a getter but no setter, so balance is read-only:
try { a.balance = 5 } catch (e) { console.log(e.name + ": " + e.message) }
// TypeError: Cannot set property balance of [object Object] which has only a getter
That error appears because class bodies and modules run in strict mode. In old sloppy-mode scripts, the assignment would fail silently, which is much harder to debug. Use a setter when you want to validate input on assignment, for example set email(v) { if (!v.includes("@")) throw ...; this.#email = v; }.
Static members
static puts a property or method on the class itself rather than on instances. In our example, Account.count tracks how many accounts were created, and Account.compare works as a sort comparator:
const s = new Savings("Ravi", 1000, 0.05).addInterest();
console.log(Account.count); // 2
console.log([s, a].sort(Account.compare).map(x => x.owner)); // [ 'Asha', 'Ravi' ]
Static members suit factory methods such as User.fromJSON(), shared constants, and helpers that work across instances. You cannot call a static method on an instance, so a.compare is undefined. For more on comparators, see our JavaScript sort guide.
Inheritance with extends and super
class Savings extends Account {
constructor(owner, opening, rate) {
super(owner, opening); // must run before using this
this.rate = rate;
}
addInterest() { return this.deposit(this.balance * this.rate); }
toString() { return `${super.toString()} (savings ${this.rate * 100}%)`; }
}
console.log(String(s));
// Ravi: 1050 (savings 5%)
Three rules to remember:
- A subclass constructor must call
super()before it touchesthis. Otherwise you get aReferenceError. super.method()calls the parent version, which is howtoString()above extends rather than replaces the parent output.- The subclass cannot read the parent’s
#balancedirectly. It goes through the publicbalancegetter anddeposit(), which keeps the parent in control of its own data.
Count went to 2 because the Savings constructor called the parent constructor through super(). Keep inheritance shallow. One level, as here, is easy to follow. Deep chains get fragile, and composition, meaning an object that holds other objects, is often simpler.
Classes are still prototypes
console.log(s instanceof Account, Object.getPrototypeOf(Savings) === Account, typeof Account);
// true true function
console.log(Object.getOwnPropertyNames(Account.prototype));
// [ 'constructor', 'deposit', 'balance', 'toString' ]
A class is a special function, and its methods sit on Account.prototype, exactly as with the old pattern. Static compare is missing from that list because it lives on Account itself. Knowing this explains a lot of behaviour, including why methods are shared and how instanceof works.
The lost this problem
Methods do not remember their object. If you pull a method out and call it alone, this is undefined:
class Btn {
label = "OK";
handle() { return this?.label }
arrow = () => this.label
}
const b = new Btn();
const { handle, arrow } = b;
console.log(handle(), arrow());
// undefined OK
This bites when you pass a method as a callback, for example to addEventListener or setTimeout. Two fixes: write the method as an arrow function field, as arrow above, which captures this per instance, or bind it with this.handle = this.handle.bind(this) in the constructor. Our guide to the this keyword explains the rules in depth.
Errors you will see
| Code | Error from our run | Cause |
|---|---|---|
Account("x") |
TypeError: Class constructor Account cannot be invoked without ‘new’ | Forgot new |
new Hoisted() before the class line |
ReferenceError: Cannot access ‘Hoisted’ before initialization | Classes are not usable before their declaration |
a.deposit(-1) |
RangeError: amount must be positive | Our own validation |
a.balance = 5 |
TypeError: … which has only a getter | No setter defined |
When should you use classes?
Use a class when many objects share behaviour and state, when you want real privacy with # fields, or when a framework expects one, such as page objects in Playwright test suites. Our Page Object Model guide shows that pattern. Prefer plain objects and functions for simple data, one-off helpers and code where a closure is enough. Our closures guide shows how closures also give you private state.
Best practices
- Use
#fields for internal state instead of underscore names. - Validate in the constructor and setters so an object can never be in a bad state.
- Keep classes small and focused on one job.
- Prefer composition over deep inheritance chains.
- Use arrow function fields for methods that will be passed as callbacks.
- In TypeScript, the same syntax works, with extra checks. See our TypeScript tutorial.
Static initialization blocks
When a static property needs more than a one-line value, use a static { } block. It runs once, when the class is defined:
class Config {
static defaults;
static {
Config.defaults = Object.freeze({ retries: 3, timeout: 5000 });
console.log("static block ran");
}
}
console.log(Config.defaults, Object.isFrozen(Config.defaults));
// static block ran
// { retries: 3, timeout: 5000 } true
Static blocks can also read private static fields, which makes them handy for setting up lookup tables or validating configuration before any instance exists.
Final thoughts
JavaScript classes give structure without hiding how the language works underneath. Declare fields at the top, make internal state private with #, expose it through getters and methods, use static for class-level helpers, and inherit with extends and super() only when it truly fits. Remember that a class is still a function with a prototype, and most of the surprising behaviour will make sense.
FAQ
Are JavaScript classes just syntactic sugar?
Mostly. They are built on prototypes and typeof a class is function. But they add real features such as private fields, strict mode by default and a required new keyword.
How do I make a private property in a JavaScript class?
Start the field name with a hash, as in #balance. Only code inside the class body can read or write it, and the engine enforces this.
What does super do in JavaScript?
In a subclass constructor, super calls the parent constructor and must run before you use this. In methods, super.method calls the parent version of that method.
What is a static method in a JavaScript class?
A static method belongs to the class itself, not to instances. You call it as ClassName.method, which suits factories and helpers.
Are JavaScript classes hoisted?
The declaration is hoisted but not initialized, so using a class before its line throws a ReferenceError. Always declare classes before you use them.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.