After this lesson you can describe a kind of thing once, as a class, and then create as many objects of that kind as you like. You will write constructors, methods, getters, static members and private fields, and you will know why this sometimes goes missing.
You already know plain objects from Objects and methods from Methods and this. A class is a tidy way to stamp out many objects that share the same shape and behaviour.
Why classes exist
Imagine a shop with fifty customers. Writing fifty object literals by hand, each with its own copy of the same logic, is tiring and error prone. A class lets you write the shape and the behaviour once.
class Customer {
constructor(name, city) {
this.name = name;
this.city = city;
}
greet() {
return `Hello, ${this.name} from ${this.city}`;
}
}
const first = new Customer("Asha", "Pune");
console.log(first.greet()); // Hello, Asha from PuneRead it in three pieces. The word class followed by a name (capitalised by convention) starts the blueprint. The constructor is a special method that runs when you write new Customer(...); inside it, this is the brand new object, so this.name = name stores a property on it. The greet method has no function keyword and no commas between members.
When you write new Customer("Asha", "Pune"), JavaScript creates an empty object, runs the constructor with this pointing at it, and hands the object back. Every object made this way shares the same greet method instead of getting its own copy.
A first class you can run
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
const small = new Rectangle(2, 3);
const big = new Rectangle(10, 20);
log("small area:", small.area());
log("big area:", big.area());
log("same method shared:", small.area === big.area);
</script>small area: 6
big area: 200
same method shared: trueThe last line shows that both rectangles use one shared area function. Change the numbers in the editor and watch the result update.
The small log helper at the top writes into the page, because the editor preview has no visible console. We use it in many lessons from here on.
Getters, static members and private fields
Here is a bigger class that uses the other class features. It runs in Node and in the browser.
class BankAccount {
#balance = 0; // private field
static count = 0; // belongs to the class
constructor(owner, opening = 0) {
this.owner = owner;
this.#balance = opening;
BankAccount.count++;
}
deposit(amount) {
if (amount <= 0) throw new Error("Deposit must be positive");
this.#balance += amount;
return this; // lets calls chain
}
get balance() { // a getter: read like a property
return this.#balance;
}
describe() {
return `${this.owner} has ${this.#balance}`;
}
static compare(a, b) { // a static method
return a.balance - b.balance;
}
}
const a = new BankAccount("Asha", 100);
a.deposit(50).deposit(25);
console.log(a.describe()); // Asha has 175
console.log(a.balance); // 175
console.log(BankAccount.count); // 1
const b = new BankAccount("Ravi");
console.log(BankAccount.compare(a, b)); // 175Going through the new pieces:
- Private field.
#balancecan only be read or written by code inside the class body. Outside,a.#balanceis a syntax error, so nobody can set a negative balance behind your back. The only way in is through your methods, which can check the input. - Getter.
get balance()lets you writea.balancewithout parentheses. There is no setter here, so assigninga.balance = 5does nothing in ordinary scripts and throws a TypeError in strict mode or inside modules. The balance stays 175 either way. - Static.
static countandstatic comparebelong to the class itself. You reach them asBankAccount.count, never through an instance. They suit counters and helper functions that do not need a particular object. - Returning this.
depositreturnsthisso you can chain calls, as ina.deposit(50).deposit(25).
A class is still a function underneath
typeof BankAccount is "function". Classes are mostly a cleaner way to write the older constructor-function pattern, and the methods really do live on a shared prototype object. The Prototypes lesson shows what that means. Two practical results follow:
- A class must be called with
new.BankAccount("x")throwsTypeError: Class constructor BankAccount cannot be invoked without 'new'. a instanceof BankAccountistrue, which is handy for checking what kind of object you were given.
Also notice that Object.keys(a) only lists owner. Methods live on the prototype, the getter likewise, and private fields are hidden, so only own public properties show up.
When this goes missing
Methods rely on this being the object they were called on. Pull a method out of its object and that link breaks.
class Counter {
count = 0;
inc() { this.count++; }
}
const c = new Counter();
const f = c.inc;
f(); // TypeError: Cannot read properties of undefined (reading 'count')Calling f() has no object in front of the dot, so this is undefined inside class code. This bites hardest when you pass a method as a callback, for example to an event listener. Two fixes work. You can bind it, c.inc.bind(c), or you can define the method as an arrow-function field:
class Counter2 {
count = 0;
inc = () => { this.count++; };
}
const c2 = new Counter2();
const g = c2.inc;
g(); g();
console.log(c2.count); // 2The arrow function captures this from the moment the object is created. The cost is that each object gets its own copy of inc, so use this form only where you need it.
Should you use classes?
Not always. A plain object and a few functions are often simpler. Classes earn their place when you create many objects of one kind, each with its own data and behaviour, or when you want to enforce rules with private fields. Many working JavaScript programmers use classes lightly and rely on functions and objects for most things.
Common mistakes
- Forgetting
new. The error message is clear once you know it. Always writenew ClassName(...). - Forgetting
this.inside the constructor. Writingname = name;assigns the parameter to itself and the object ends up with nothing. You needthis.name = name;. - Putting commas between methods. Object literals use commas, class bodies do not. A comma in a class body is a syntax error.
- Using
thisbeforesuper()in a subclass. You will meet this in Inheritance with extends. - Passing a method as a callback and losing
this. Bind it or use an arrow-function field. - Expecting private fields to be hidden for security. They stop accidental use inside your own program. They do not protect anything from a person who can run code on the page.
Exercise
Write a class Temperature whose constructor takes a value in Celsius. Add a getter fahrenheit that returns the converted value (multiply by 9, divide by 5, add 32) and a static method fromFahrenheit(f) that returns a new Temperature. Create one from 100 Celsius and print its Fahrenheit value (it should be 212), then create one with Temperature.fromFahrenheit(32) and check its Celsius value is 0.
Next, learn how one class can build on another in Inheritance with extends.
Key points
- A class is a blueprint; new ClassName(...) runs the constructor and returns a fresh object.
- Methods written in the class body are shared by every object made from it.
- A getter reads like a property but runs code, and a field starting with
- static members belong to the class itself, not to the objects it creates.
- A method that loses its object (const f = obj.method) loses this as well.