JavaScriptAdvanced

JavaScript Classes: constructor, Methods, Getters and static

Learn JavaScript classes step by step: constructor, instance methods, getters and setters, static methods, and how classes work on top of prototypes.

All JavaScript lessons (83)View curriculum

What you will learn

In the last lesson you wrote constructor functions, added methods to Constructor.prototype, and used new. It works well, but it has some clumsy parts: the methods are written outside the constructor, and a small mistake (like forgetting new) can cause strange bugs.

Classes give you a cleaner, safer way to write exactly the same thing. In this lesson you will learn how to write a class, how the constructor and instance methods work, how getters and setters let you control reading and writing, and how static methods belong to the class itself. You will also see that a class is built on the prototypes you already know, so nothing here is magic.

The idea in one line

A class is a blueprint for objects. You write the data setup and the methods together in one block, and new builds objects from it.

Think of an architect’s plan for a house. The plan is not a house. But from one plan you can build many houses, and every house has the same rooms. A class is the plan, and each object made with new is a house.

From constructor function to class

Here is the Person from the last lesson:

function Person(userName, age) {
  this.userName = userName;
  this.age = age;
}

Person.prototype.greet = function () {
  return "Hi, I am " + this.userName;
};

And here is the same thing as a class:

class Person {
  constructor(userName, age) {
    this.userName = userName;
    this.age = age;
  }

  greet() {
    return "Hi, I am " + this.userName;
  }
}

const riya = new Person("Riya", 21);
const karan = new Person("Karan", 25);

console.log(riya.greet());     // "Hi, I am Riya"
console.log(karan.greet());    // "Hi, I am Karan"

Everything is inside one { } block. Notice the small rules:

  • You write the keyword class and a name with a capital letter.
  • The setup code goes in a special method called constructor.
  • Methods are written without the word function.
  • There are no commas between methods.

Proof: a class is built on prototypes

A class does not replace prototypes. It is a nicer way to write them. Check it with what you learned in the prototypes lesson:

console.log(typeof Person);                                       // "function"  (a class IS a function)
console.log(Object.hasOwn(riya, "greet"));                        // false (greet is not an own property)
console.log(riya.greet === karan.greet);                          // true  (one shared copy)
console.log(Object.getPrototypeOf(riya) === Person.prototype);    // true
console.log(Object.hasOwn(Person.prototype, "greet"));            // true  (greet lives on the prototype)
console.log(riya instanceof Person);                              // true

So the methods you write in a class go to Person.prototype, exactly like before. One copy, shared by all objects. The constructor method is the constructor function body.

The constructor method

The constructor runs once for every new. Its job is to set up the new object: create the instance properties.

class Product {
  constructor(title, price) {
    this.title = title;
    this.price = price;
    this.createdAt = new Date();   // computed when the object is created
  }
}

const pen = new Product("Pen", 20);

console.log(pen.title);                    // "Pen"
console.log(pen.createdAt instanceof Date); // true
  • Inside the constructor, this is the new object (the same four-step new process from the last lesson).
  • A class can have only one constructor.
  • If you do not write one, JavaScript adds an empty one for you.
  • You do not return anything from it.

Default values and checks

You can use default parameters and throw an error when the data is wrong, so a bad object is never created:

class User {
  constructor(userName, role = "student") {
    if (typeof userName !== "string" || userName.trim() === "") {
      throw new TypeError("userName must be a non-empty string");
    }
    this.userName = userName;
    this.role = role;
  }
}

const riya = new User("Riya");
console.log(riya.role);   // "student"

try {
  new User("");
} catch (error) {
  console.log(error.name + ": " + error.message);   // "TypeError: userName must be a non-empty string"
}

Instance methods

Any function you write inside the class (other than constructor) is an instance method. It is shared through the prototype, and this is the object before the dot.

class Counter {
  constructor() {
    this.count = 0;
  }

  increase() {
    this.count++;
    return this;       // return this: allows chaining
  }

  decrease() {
    this.count--;
    return this;
  }

  show() {
    console.log("Count is " + this.count);
  }
}

const likes = new Counter();
likes.increase().increase().increase().decrease().show();   // "Count is 2"

Methods can call other methods with this:

class Cart {
  constructor() {
    this.items = [];
  }

  add(name, price) {
    this.items.push({ name, price });
    return this;
  }

  total() {
    return this.items.reduce((sum, item) => sum + item.price, 0);
  }

  summary() {
    return this.items.length + " items, total Rs. " + this.total();   // calls another method
  }
}

const cart = new Cart();
cart.add("Pen", 10).add("Bag", 450);

console.log(cart.summary());   // "2 items, total Rs. 460"

The lost this problem is still here

A class method passed as a callback loses its this, just like before. In a class it is even stricter: code inside a class always runs in strict mode (you learned about strict mode earlier), so the lost this is undefined and you get a TypeError.

const increase = likes.increase;

try {
  increase();
} catch (error) {
  console.log(error.name);   // "TypeError" (this is undefined)
}

You already know the fixes from the call, apply and bind lesson:

setTimeout(() => likes.increase(), 500);          // arrow wrapper
setTimeout(likes.increase.bind(likes), 500);      // bind

A third fix, often used for event handlers, is to bind the method once in the constructor:

class Button {
  constructor(label) {
    this.label = label;
    this.handleClick = this.handleClick.bind(this);   // lock this for this object
  }

  handleClick() {
    console.log("Clicked: " + this.label);
  }
}

const save = new Button("Save");
setTimeout(save.handleClick, 300);   // "Clicked: Save"  (this is kept)

Class fields: a shorter way to create properties

Instead of writing this.count = 0; in the constructor, you can declare a property directly in the class body. This is called a class field.

class Counter {
  count = 0;          // a public instance property, created for every object

  increase() {
    this.count++;
    return this;
  }
}

const c = new Counter();
c.increase().increase();

console.log(c.count);   // 2

Class fields are also a clean way to solve the lost this problem. If the field is an arrow function, it uses the this of the object being created:

class Button {
  label = "Save";

  handleClick = () => {
    console.log("Clicked: " + this.label);
  };
}

const save = new Button();
const handler = save.handleClick;

handler();   // "Clicked: Save"  (this is never lost)

Good to know: a field written this way (an arrow function) is created separately for every object. It is not shared on the prototype like a normal method. This is a good trade for event handlers, but not for methods that you create thousands of times.

Getters and setters

Sometimes you want something that looks like a property but runs code. For example, a fullName made from firstName and lastName, or an age that must never be negative. Getters and setters do this.

What they are (in a plain object first)

A getter is a function that runs when you read a property. A setter runs when you assign to it. You write them with the words get and set:

const person = {
  firstName: "Riya",
  lastName: "Sharma",

  get fullName() {
    return this.firstName + " " + this.lastName;
  },

  set fullName(value) {
    const parts = value.split(" ");
    this.firstName = parts[0];
    this.lastName = parts[1];
  }
};

console.log(person.fullName);       // "Riya Sharma"  (no brackets! the getter ran)

person.fullName = "Karan Mehta";    // the setter ran
console.log(person.firstName);      // "Karan"
console.log(person.lastName);       // "Mehta"

From the outside, person.fullName looks like a normal property. But there is no stored fullName. It is calculated every time you read it.

Getters and setters in a class

They work the same way in a class, and they live on the prototype like methods:

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  get area() {
    return this.width * this.height;    // calculated when you read it
  }

  get isSquare() {
    return this.width === this.height;
  }
}

const box = new Rectangle(4, 5);

console.log(box.area);        // 20   (no brackets)
console.log(box.isSquare);    // false

box.width = 5;
console.log(box.area);        // 25   (always up to date)
console.log(box.isSquare);    // true

Because area is calculated on request, it can never be out of date. If you stored this.area = width * height in the constructor, it would become wrong as soon as width changed.

A setter that checks the value

A setter can protect your data by checking it before saving:

class Student {
  constructor(userName, marks) {
    this.userName = userName;
    this.marks = marks;          // this goes through the setter below
  }

  get marks() {
    return this._marks;
  }

  set marks(value) {
    if (typeof value !== "number" || value < 0 || value > 100) {
      throw new RangeError("Marks must be a number from 0 to 100");
    }
    this._marks = value;
  }
}

const riya = new Student("Riya", 85);
console.log(riya.marks);    // 85

try {
  riya.marks = 150;
} catch (error) {
  console.log(error.name + ": " + error.message);   // "RangeError: Marks must be a number from 0 to 100"
}

Two important details:

  • The real value is stored in _marks (with an underscore). The getter and setter share it. We must use a different name, because if the setter wrote this.marks = value, it would call itself again and again, forever.
  • Even this.marks = marks in the constructor uses the setter, so the check also protects new objects.

Good to know: the underscore (_marks) is only a polite signal: “please do not touch this directly”. Anyone can still write riya._marks = 999. In the lessons ahead you will learn how to make a value truly private.

A getter without a setter is read-only

If you write only a getter, the property can be read, but not changed:

class Circle {
  constructor(radius) {
    this.radius = radius;
  }

  get diameter() {
    return this.radius * 2;
  }
}

const circle = new Circle(5);
circle.diameter = 100;           // ignored in normal mode, TypeError in strict mode

console.log(circle.diameter);    // 10  (unchanged)

This is a neat way to make calculated, read-only values.

When to use a getter, and when a method

Use a getter when Use a method when
It feels like a value (area, fullName, total) It feels like an action (save(), send())
It is quick and has no side effects It does heavy work or changes something
It takes no arguments It needs arguments

Static methods

So far every method belonged to an object. A static method belongs to the class itself. You call it on the class name, not on an object.

class MathHelper {
  static square(n) {
    return n * n;
  }

  static average(numbers) {
    return numbers.reduce((sum, n) => sum + n, 0) / numbers.length;
  }
}

console.log(MathHelper.square(6));          // 36
console.log(MathHelper.average([4, 8, 9])); // 7

You already use static methods every day: Array.isArray(), Object.keys(), Date.now(), Number.isInteger(), Promise.all(). They are tools that belong to the category, not to one specific value.

An object cannot use them:

const helper = new MathHelper();

console.log(typeof helper.square);   // "undefined" (static methods are not on the objects)

Static factory methods

A very common use is a factory method: a static method that creates objects in a special way.

class User {
  constructor(userName, email) {
    this.userName = userName;
    this.email = email;
  }

  static fromString(text) {          // "Riya,[email protected]"
    const [userName, email] = text.split(",");
    return new User(userName, email);
  }

  static compare(a, b) {             // useful for sorting
    return a.userName.localeCompare(b.userName);
  }
}

const riya = User.fromString("Riya,[email protected]");
console.log(riya.email);   // "[email protected]"

const users = [new User("Zoya", "[email protected]"), new User("Aman", "[email protected]")];
users.sort(User.compare);
console.log(users[0].userName);   // "Aman"

Remember: inside a static method, this is the class itself (the thing before the dot), not an object. So you do not use this.userName there.

You can compare this with the “properties on the constructor” idea from the last lesson. static is the clean class version of Student.compare = function () {}.

Classes vs constructor functions

Classes are built on constructors and prototypes, but with some safety improvements:

Constructor function Class
Called without new Runs quietly, may create globals Throws a TypeError
Strict mode Only if you ask Always strict inside
Methods enumerable (show in for...in) Yes (when added by assignment) No
Hoisted (usable before the line) Yes, function declarations No (like let)
Getters, setters, static, fields Awkward Built in

See these in action:

class Person {
  constructor(userName) {
    this.userName = userName;
  }

  greet() {
    return "Hi " + this.userName;
  }
}

// 1. You cannot forget new
try {
  Person("Riya");
} catch (error) {
  console.log(error.message);   // "Class constructor Person cannot be invoked without 'new'"
}

// 2. Methods do not show up in for...in
const riya = new Person("Riya");
for (const key in riya) {
  console.log(key);   // only "userName" (not greet)
}
// 3. A class cannot be used before it is written
try {
  const early = new Later();
} catch (error) {
  console.log(error.name);   // "ReferenceError"
}

class Later {}

This is the same “temporal dead zone” behaviour you know from let and const in the scope and hoisting lesson.

Class expressions

Like functions, a class can be written as an expression, and stored in a variable:

const Animal = class {
  speak() {
    return "...";
  }
};

console.log(new Animal().speak());   // "..."

You will mostly write class declarations (class Name { }). Just know the other form exists.

toString and template strings

Defining toString on a class controls how objects look as text:

class Product {
  constructor(title, price) {
    this.title = title;
    this.price = price;
  }

  toString() {
    return this.title + " - Rs. " + this.price;
  }
}

const pen = new Product("Pen", 20);

console.log(`Today's offer: ${pen}`);   // "Today's offer: Pen - Rs. 20"
console.log(String(pen));               // "Pen - Rs. 20"

Real-life use cases

1. A bank account with rules

class BankAccount {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }

  deposit(amount) {
    if (amount <= 0) {
      throw new RangeError("Deposit must be more than 0");
    }
    this.balance += amount;
    return this;
  }

  withdraw(amount) {
    if (amount > this.balance) {
      throw new Error("Not enough balance");
    }
    this.balance -= amount;
    return this;
  }
}

const account = new BankAccount("Riya", 1000);
account.deposit(500).withdraw(200);

console.log(account.balance);   // 1300

try {
  account.withdraw(5000);
} catch (error) {
  console.log(error.message);   // "Not enough balance"
}

2. A temperature converter with a getter and setter

class Temperature {
  constructor(celsius) {
    this.celsius = celsius;
  }

  get fahrenheit() {
    return (this.celsius * 9) / 5 + 32;
  }

  set fahrenheit(value) {
    this.celsius = ((value - 32) * 5) / 9;
  }
}

const t = new Temperature(100);
console.log(t.fahrenheit);   // 212

t.fahrenheit = 32;
console.log(t.celsius);      // 0

3. A to-do list

class TodoList {
  constructor() {
    this.tasks = [];
    this.nextId = 1;
  }

  add(text) {
    this.tasks.push({ id: this.nextId++, text, done: false });
    return this;
  }

  complete(id) {
    const task = this.tasks.find((t) => t.id === id);
    if (task) task.done = true;
    return this;
  }

  get remaining() {
    return this.tasks.filter((t) => !t.done).length;
  }
}

const list = new TodoList();
list.add("Learn classes").add("Practice").add("Build project");
list.complete(1);

console.log(list.remaining);   // 2

4. A stopwatch that safely keeps this

class Stopwatch {
  seconds = 0;
  timerId = null;

  start() {
    this.timerId = setInterval(() => {      // arrow function keeps this
      this.seconds++;
      console.log("Seconds: " + this.seconds);
    }, 1000);
  }

  stop() {
    clearInterval(this.timerId);
  }
}

const watch = new Stopwatch();
watch.start();
setTimeout(() => watch.stop(), 3500);   // prints 1, 2, 3 and stops

5. Reading data from a server response

class Post {
  constructor(id, title, body) {
    this.id = id;
    this.title = title;
    this.body = body;
  }

  get preview() {
    return this.body.length > 30 ? this.body.slice(0, 30) + "..." : this.body;
  }

  static fromApi(data) {                  // turn plain data into a Post object
    return new Post(data.id, data.title, data.body);
  }
}

// Imagine this came from fetch(...).then(r => r.json())
const data = { id: 1, title: "Hello", body: "This is a long post body that needs a preview" };

const post = Post.fromApi(data);
console.log(post.preview);   // "This is a long post body that ..."

Plain JSON data has no methods. Wrapping it in a class gives it behaviour, like preview.

Common mistakes

  • Putting commas between methods (greet() {}, hello() {}). Class methods are not separated by commas. It is a SyntaxError.
  • Forgetting new. A class throws a TypeError. Always write new ClassName(...).
  • Using this without the object inside methods, such as writing count++ instead of this.count++.
  • Passing a method as a callback and losing this. Use an arrow wrapper, bind, or an arrow-function class field.
  • Writing a getter with brackets (box.area()). A getter is read like a property: box.area.
  • Giving a getter and its stored value the same name. get marks() { return this.marks; } calls itself forever. Store it as _marks.
  • Writing a setter without a getter and then reading the property. It gives undefined.
  • Calling a static method on an object (riya.fromString(...)). Call it on the class: User.fromString(...).
  • Using this.instanceProperty inside a static method. There, this is the class, not an object.
  • Using the class before its definition. Classes are not hoisted for use.
  • Using an arrow-function field for every method (greet = () => {}). It creates a separate copy for every object. Use a normal method, and keep arrow fields for handlers that need a fixed this.
  • Putting arrays or objects as shared defaults instead of creating them per object in the constructor or as a field.

Practice

  1. Write a Book class with a constructor(title, author, price) and a method describe() that returns "<title> by <author>".
  2. Create two books. Prove that describe is shared (book1.describe === book2.describe) and that it is not an own property (Object.hasOwn).
  3. Print typeof Book, Object.getPrototypeOf(book1) === Book.prototype and book1 instanceof Book. Explain each result in your own words.
  4. Try to call Book("x", "y", 1) without new and read the error. Then try the same with a constructor function and compare.
  5. Add a getter isExpensive that returns true when price > 500. Read it without brackets.
  6. Add a setter price that throws a RangeError when the value is negative. Remember to store the value as _price.
  7. Make a class with a getter but no setter. Try to assign to it, and check the result in normal mode and with "use strict" at the top.
  8. Write a Counter class where every method returns this. Chain five calls in one line.
  9. Take a method from a class object into a variable and call it. Read the error. Fix it in three ways: arrow wrapper, bind and an arrow-function class field.
  10. Add a static method Book.cheapest(books) that returns the cheapest book from an array. Call it on the class, then try to call it on a book and read the result.
  11. Write a static factory Book.fromString("JS Basics|Riya|350") using split and destructuring.
  12. Write a toString() for your book and use it inside a template string.
  13. Use for...in over a book. Which keys appear? Why is describe missing?
  14. Challenge: write a Cart class with add(name, price, qty), a getter total, a getter count, and a method clear(). Make add chainable.
  15. Challenge: write a Temperature class with celsius, a fahrenheit getter and setter, and a static fromFahrenheit. Test that converting back and forth gives the same number.
  16. Challenge: rewrite a constructor function with prototype methods from the previous lesson as a class. Compare both with Object.getPrototypeOf and check that the results are the same.

Recap

  • A class is a blueprint for objects. It is a cleaner way to write constructor functions and prototypes. typeof a class is "function", and its methods live on ClassName.prototype.
  • The constructor method runs once for each new and sets up the instance properties with this. A class can have only one.
  • Methods written in the class body are instance methods: shared through the prototype, with this being the object before the dot. No commas between them.
  • Class fields (count = 0;) declare instance properties in the class body. An arrow function field keeps this fixed for event handlers.
  • Getters (get name() {}) run when a property is read, setters (set name(v) {}) run when it is assigned. Use a getter for calculated values, and a setter to validate. Store the real value under another name, such as _name.
  • A getter only gives a read-only property.
  • static methods belong to the class: ClassName.method(). In them, this is the class. Great for helpers, comparers and factory methods.
  • Classes are safer than plain constructors: they need new, run in strict mode, are not hoisted for use, and their methods do not show up in for...in.
  • Passing a class method as a callback still loses this. Fix it with an arrow wrapper, bind or an arrow field.
  • Next you will learn class inheritance: how one class can extend another, reuse its code and change what it needs, with extends and super.

If you want to revisit the basics, read the constructor functions lesson, the prototypes lesson, the this keyword lesson and the strict mode lesson.

Frequently asked questions

What is a class in JavaScript?

A class is a blueprint for creating objects. You write the setup in a constructor and the behaviour as methods, then create objects with new. Under the hood, a class is a function, and its methods are stored on its prototype.

Is a JavaScript class the same as a constructor function?

They do almost the same job, and both use prototypes. Classes have a cleaner syntax and extra safety: they must be called with new, always run in strict mode, and do not make methods enumerable.

What does the constructor method do?

It runs automatically each time you create an object with new. Inside it, this is the new object, so you use it to set the initial properties. If you do not write one, JavaScript uses an empty constructor.

What are getters and setters used for?

A getter lets you read a calculated value like a normal property, such as rectangle.area. A setter lets you run code when someone assigns to a property, so you can check or convert the value before saving it.

What is a static method?

A static method belongs to the class and not to its objects. You call it on the class name, like User.fromString(text). Built-in examples are Array.isArray() and Date.now().

Why do I get "this is undefined" in my class method?

You probably passed the method as a callback or stored it in a variable. It was then called without its object, and class code is strict, so this is undefined. Use an arrow function wrapper, bind, or an arrow function class field.

See also: Constructor Functions, Prototypes, Call, Apply and Bind, JavaScript Cheat Sheet