JavaScript Classes: Constructor, Methods, Fields and Static Members

A class is a blueprint for creating many objects with the same shape and behaviour: many test cases, many users, many pages. Classes are the backbone of the Page Object Model used in almost every Playwright, Selenium and WebdriverIO framework. In this lesson you will learn how to write a class with a constructor, methods and fields, create objects with new, use static members for shared helpers, and avoid the common class mistakes, ending with a small page object.

Advertisement

📖 What You’ll Learn: class syntax, the constructor, creating instances with new, instance methods, class fields, method chaining, static methods and fields, static blocks, class expressions, this inside classes and callbacks, classes versus factory functions, and building a page object class.


🏗️ Class Syntax and the Constructor

Definition: a class is a template for creating objects. Each object created from it is an instance. The special constructor method runs once when an instance is created with new, and usually sets the instance’s properties.

📄 class.js

class User {
  constructor(name, role = "tester") {
    this.name = name;          // this = the new instance
    this.role = role;
    this.createdAt = "2026-11-23";
  }
}

const asha = new User("Asha");
const ravi = new User("Ravi", "admin");

console.log(asha);
console.log(ravi.role, asha instanceof User, typeof User);

⌨️ Terminal

node class.js

🖥️ Output

User { name: 'Asha', role: 'tester', createdAt: '2026-11-23' }
admin true function
  • Class names use PascalCase: User, LoginPage, ApiClient.
  • A class can have only one constructor. If you omit it, an empty one is used.
  • Class bodies always run in strict mode.

Unlike constructor functions, classes must be called with new, and they are not hoisted for use before their definition:

📄 no-new.js

class Report {}
try {
  Report();
} catch (e) {
  console.log(e.constructor.name + ":", e.message);
}

⌨️ Terminal

node no-new.js

🖥️ Output

TypeError: Class constructor Report cannot be invoked without 'new'

🛠️ Instance Methods

Methods are written inside the class body without the function keyword. They are stored once on the prototype and shared by all instances (see the Prototypes lesson).

📄 methods.js

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

  add(name, price, qty = 1) {
    this.items.push({ name, price, qty });
    return this;                 // return this to allow chaining
  }

  remove(name) {
    this.items = this.items.filter((i) => i.name !== name);
    return this;
  }

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

  get count() {                  // a getter, covered in lesson 41
    return this.items.length;
  }
}

const cart = new Cart().add("Pen", 10, 3).add("Lamp", 899).add("Mug", 199).remove("Mug");
console.log(cart.total(), cart.count);
console.log(Object.keys(cart), typeof Cart.prototype.add);

⌨️ Terminal

node methods.js

🖥️ Output

929 2
[ 'items' ] function

Advertisement

📋 Class Fields

Class fields (ES2022) declare instance properties directly in the class body, with optional initial values. Each instance gets its own copy. They make the shape of an object visible at a glance:

📄 fields.js

class TestRun {
  status = "pending";             // field with a default value
  results = [];                   // each instance gets its own array
  startedAt;                      // declared, initially undefined

  constructor(suite) {
    this.suite = suite;
    this.startedAt = new Date(Date.UTC(2026, 10, 23, 10)).toISOString();
  }

  record(test, passed) {
    this.results.push({ test, passed });
    this.status = this.results.every((r) => r.passed) ? "passing" : "failing";
  }
}

const a = new TestRun("smoke");
const b = new TestRun("regression");
a.record("login", true);
b.record("cart", false);
console.log(a.status, a.results.length, "|", b.status, b.results.length);
console.log(a);

⌨️ Terminal

node fields.js

🖥️ Output

passing 1 | failing 1
TestRun {
  status: 'passing',
  results: [ { test: 'login', passed: true } ],
  startedAt: '2026-11-23T10:00:00.000Z',
  suite: 'smoke'
}

💡 Tip: Field initialisers run for every new instance, before the constructor body. So results = [] gives every instance a separate array, unlike a value shared on the prototype.


🏷️ Static Methods and Fields

Definition: a static member belongs to the class itself, not to its instances. Call it on the class (ClassName.method()). Static members are used for helpers, factory methods, constants and counters that relate to the class as a whole.

📄 static.js

class User {
  static count = 0;                       // static field: shared by the class
  static ROLES = ["viewer", "tester", "admin"];

  constructor(name, role) {
    if (!User.ROLES.includes(role)) throw new Error(`Invalid role: ${role}`);
    this.name = name;
    this.role = role;
    User.count++;
  }

  static fromEmail(email) {               // static factory method
    const name = email.split("@")[0];
    return new User(name, "viewer");
  }

  static compareByName(a, b) {
    return a.name.localeCompare(b.name);
  }
}

const users = [new User("ravi", "admin"), User.fromEmail("asha@sqatools.in"), new User("meera", "tester")];
console.log(User.count, users.toSorted(User.compareByName).map((u) => u.name));
console.log(typeof users[0].fromEmail);    // not available on instances

try {
  new User("x", "superuser");
} catch (e) {
  console.log(e.message);
}

⌨️ Terminal

node static.js

🖥️ Output

3 [ 'asha', 'meera', 'ravi' ]
undefined
Invalid role: superuser

Math.max, Array.from, Object.keys and Date.now are all static methods of built-in classes.

Static initialisation blocks

A static { ... } block (ES2022) runs once when the class is defined, for setup that needs more than a single expression:

📄 static-block.js

class Config {
  static values;
  static {
    const env = process.env.TEST_ENV ?? "qa";
    Config.values = { env, baseURL: `https://${env}.example.com` };
  }
}
console.log(Config.values);

⌨️ Terminal

node static-block.js

🖥️ Output

{ env: 'qa', baseURL: 'https://qa.example.com' }

🎯 this Inside Classes

Inside a method, this is the instance the method was called on. If you pass a method somewhere as a callback, it loses that connection, and because classes are strict, this becomes undefined:

📄 this.js

class Logger {
  prefix = "[test]";
  log(message) {
    return `${this.prefix} ${message}`;
  }
  logArrow = (message) => `${this.prefix} ${message}`;   // arrow field keeps this
}

const logger = new Logger();
const messages = ["start", "end"];

try {
  messages.map(logger.log);
} catch (e) {
  console.log("method as callback:", e.message);
}
console.log(messages.map((m) => logger.log(m)));   // fix 1: arrow wrapper
console.log(messages.map(logger.log.bind(logger))); // fix 2: bind
console.log(messages.map(logger.logArrow));          // fix 3: arrow-function field

⌨️ Terminal

node this.js

🖥️ Output

method as callback: Cannot read properties of undefined (reading 'prefix')
[ '[test] start', '[test] end' ]
[ '[test] start', '[test] end' ]
[ '[test] start', '[test] end' ]

The this, call, apply and bind lesson explains these rules in full.


Advertisement

🧾 Class Expressions and toString

Like functions, classes can be created as expressions and passed around as values. Defining toString() controls how an instance looks when converted to a string:

📄 expression.js

const Shape = class {
  constructor(name) { this.name = name; }
  toString() { return `Shape(${this.name})`; }
};

const s = new Shape("square");
console.log(`${s}`, String(s));

function createModel(fields) {          // a class created at runtime
  return class {
    constructor(data) {
      for (const f of fields) this[f] = data[f] ?? null;
    }
  };
}
const Order = createModel(["id", "total"]);
console.log(new Order({ id: 7 }));

⌨️ Terminal

node expression.js

🖥️ Output

Shape(square) Shape(square)
{ id: 7, total: null }

⚖️ Classes vs Factory Functions

A factory function is a normal function that returns a new object (often using closures for private state). Both styles are common:

ClassFactory function
Create withnew User()createUser()
Shared methodsOn the prototype (memory efficient)Usually recreated per object
Private state#private fieldsClosures
instanceofWorksDoes not apply
InheritanceextendsComposition / spreading objects
this pitfallsYes, when passing methodsFew, if closures are used

Test frameworks lean towards classes for page objects and API clients, and towards factory functions for test-data builders. Pick one style per job and stay consistent.


🧪 Tester Scenario: A Page Object Class

In the Page Object Model, each page of the application is a class that knows its URL and elements and offers methods for user actions. Tests call those methods instead of repeating selectors. This simulation uses a fake page object so it runs in Node.js; with Playwright the methods would await page.goto(), page.fill() and so on.

📄 login-page.js

class FakePage {                           // stands in for Playwright's page
  actions = [];
  goto(url) { this.actions.push(`goto ${url}`); }
  fill(selector, value) { this.actions.push(`fill ${selector} = ${value}`); }
  click(selector) { this.actions.push(`click ${selector}`); }
}

class LoginPage {
  static URL = "/login";
  selectors = { email: "#email", password: "#password", submit: "button[type=submit]" };

  constructor(page, baseURL) {
    this.page = page;
    this.baseURL = baseURL;
  }

  open() {
    this.page.goto(this.baseURL + LoginPage.URL);
    return this;
  }

  login(email, password) {
    this.page.fill(this.selectors.email, email);
    this.page.fill(this.selectors.password, "*".repeat(password.length));   // never log real passwords
    this.page.click(this.selectors.submit);
    return this;
  }
}

const page = new FakePage();
new LoginPage(page, "https://qa.example.com").open().login("asha@sqatools.in", "Secret@123");
console.log(page.actions.join("\n"));

⌨️ Terminal

node login-page.js

🖥️ Output

goto https://qa.example.com/login
fill #email = asha@sqatools.in
fill #password = **********
click button[type=submit]
  • Selectors live in one place: when the UI changes, only the page class changes, not every test.
  • Methods describe user intent (login), so tests read like test cases.
  • The page object is passed in (dependency injection), which makes the class easy to test with a fake, as here.

Advertisement

📝 Practice Questions with Answers

Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.

Q1. Write a class Rectangle with width and height, and methods area() and perimeter(). Print both for a 4 × 3 rectangle.

Show answer

📄 practice1.js

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  area() { return this.width * this.height; }
  perimeter() { return 2 * (this.width + this.height); }
}
const r = new Rectangle(4, 3);
console.log(r.area(), r.perimeter());

🖥️ Output

12 14

Q2. Write a class Counter with a field value = 0 and chainable methods inc(), dec() and reset().

Show answer

📄 practice2.js

class Counter {
  value = 0;
  inc() { this.value++; return this; }
  dec() { this.value--; return this; }
  reset() { this.value = 0; return this; }
}
const c = new Counter().inc().inc().inc().dec();
console.log(c.value, c.reset().value);

🖥️ Output

2 0

Q3. Add a static method Temperature.fromFahrenheit(f) to a class that stores Celsius, and print the Celsius value for 98.6 °F rounded to one decimal.

Show answer

📄 practice3.js

class Temperature {
  constructor(celsius) { this.celsius = celsius; }
  static fromFahrenheit(f) { return new Temperature(((f - 32) * 5) / 9); }
}
console.log(Temperature.fromFahrenheit(98.6).celsius.toFixed(1));

🖥️ Output

37.0

Q4. Write a class BankAccount whose withdraw(amount) throws an error when the amount is more than the balance. Show both a successful and a failed withdrawal.

Show answer

📄 practice4.js

class BankAccount {
  constructor(owner, balance = 0) {
    this.owner = owner;
    this.balance = balance;
  }
  deposit(amount) { this.balance += amount; return this.balance; }
  withdraw(amount) {
    if (amount > this.balance) throw new Error(`Insufficient funds: balance ${this.balance}, requested ${amount}`);
    this.balance -= amount;
    return this.balance;
  }
}
const acc = new BankAccount("Asha", 500);
console.log(acc.withdraw(200));
try { acc.withdraw(1000); } catch (e) { console.log(e.message); }

🖥️ Output

300
Insufficient funds: balance 300, requested 1000

Q5. Count how many Ticket objects have been created using a static field, and give each ticket an ID like "TCK-1".

Show answer

📄 practice5.js

class Ticket {
  static created = 0;
  constructor(title) {
    Ticket.created++;
    this.id = `TCK-${Ticket.created}`;
    this.title = title;
  }
}
const t1 = new Ticket("Login fails");
const t2 = new Ticket("Cart total wrong");
console.log(t1.id, t2.id, Ticket.created);

🖥️ Output

TCK-1 TCK-2 2

Q6. This code throws “Cannot read properties of undefined”. Fix it so it prints [ "Hi Asha", "Hi Ravi" ].

class Greeter {
  greeting = "Hi";
  greet(name) { return `${this.greeting} ${name}`; }
}
const g = new Greeter();
console.log(["Asha", "Ravi"].map(g.greet));
Show answer

📄 practice6.js

class Greeter {
  greeting = "Hi";
  greet(name) { return `${this.greeting} ${name}`; }
}
const g = new Greeter();
console.log(["Asha", "Ravi"].map((name) => g.greet(name)));

🖥️ Output

[ 'Hi Asha', 'Hi Ravi' ]

Passing g.greet detaches the method from g. Wrap it in an arrow function, use g.greet.bind(g), or define greet as an arrow-function field.


🧠 MCQ Quiz: Classes

10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.

  1. What runs when you call new User("Asha")?
  2. What happens if you call a class without new?
  3. Where are class methods stored?
  4. How do you call a static method?
  5. What does a class field like items = [] give each instance?
  6. Which mode does code inside a class body run in?
  7. Why might list.map(obj.method) throw?
  8. What is the main purpose of a Page Object class?
  9. What is typeof class {}?
  10. What does returning this from methods allow?

💼 Interview Questions and Answers

Q1. What is the difference between a class and an object?

A class is a blueprint: it defines the properties and methods that its objects will have. An object (instance) is a concrete value created from that blueprint with new, with its own data. In JavaScript a class is itself a function object, and instances are linked to the class’s prototype.

Q2. What is the difference between static and instance methods?

Instance methods are called on an object (user.save()) and use its data through this. Static methods are called on the class (User.fromEmail()) and do not need an instance; they are used for factories, utilities, constants and counters. Inside a static method, this refers to the class.

Q3. Why are class fields useful, and how do they differ from properties set in the constructor?

Class fields declare the instance shape in one visible place and can have default values; they run before the constructor body for each instance. Properties set in the constructor can depend on constructor arguments. Both create own properties on the instance. Arrow-function fields also bind this permanently, which is handy for callbacks, at the cost of one function per instance.

Q4. How do classes help in test automation frameworks?

They organise code by responsibility: page objects (selectors and user actions per page), API clients (endpoints and authentication), and fixtures or helpers. Constructors receive dependencies such as Playwright’s page or request, methods expose intent-based actions, and static members hold shared constants. This removes duplication and localises changes when the UI or API changes.


Advertisement

❓ Frequently Asked Questions

🤔 Can a class have more than one constructor?

No. Use default parameters, an options object, or static factory methods (User.fromEmail, User.fromJSON) for different ways of creating instances.

🤔 Are classes hoisted?

Class declarations are hoisted but stay in the temporal dead zone, so using a class before its definition throws a ReferenceError.

🤔 Should every helper be a class?

No. Use a class when you need several instances with state and behaviour (pages, clients, models). Plain functions are better for stateless helpers.

🤔 How do I print a class instance nicely?

Define a toString() method for string conversion, or a toJSON() method to control JSON.stringify output.


🏁 Summary

  • A class is a blueprint; new ClassName() runs the constructor and returns an instance.
  • Methods are shared on the prototype; class fields declare per-instance properties with defaults.
  • Static members belong to the class: use them for factories, constants and counters.
  • Classes are strict, require new, and lose this when methods are passed as callbacks.
  • Page Object classes keep selectors and actions in one place and make tests readable.

Next, continue with Lesson 40: Inheritance.

🎬 Watch JavaScript and automation tutorials on YouTube!

Subscribe to SqaToolsByDY • Practice on sqatools.in