Classes and Modules · Lesson 11 of 25
Classes, Getters and Setters in LWC
Every component you write is a class – so it pays to know classes properly. Getters are how LWC does "computed properties", setters let a component react the moment a parent changes a value, and mixins like NavigationMixin are just a clever use of inheritance. This lesson covers all of it, first in plain JavaScript and then inside components.
In this lesson
- Class syntax: fields, constructor, methods, static
- Getters as computed properties
- @api getter/setter pairs
- Inheritance, super and mixins
Class syntax in plain JavaScript
class Money {
static currency = 'INR'; // shared by the class, not each instance
#paise; // private field: invisible outside the class
constructor(rupees) {
this.#paise = Math.round(rupees * 100);
}
add(other) {
return new Money((this.#paise + other.#paise) / 100);
}
get rupees() { // getter: read like a property
return this.#paise / 100;
}
toString() {
return `${Money.currency} ${this.rupees.toFixed(2)}`;
}
}
const price = new Money(499.99);
const tax = new Money(90);
const total = price.add(tax);
console.log(String(total), total.rupees);
console.log(total.paise, Object.keys(total)); // the private field doesn't leak
console.log(total instanceof Money, typeof Money);
INR 589.99 589.99 undefined [] true function
- A class is syntax over JavaScript's prototypes –
typeof Moneyis'function'. - Fields declared at the top (
static currency,#paise) are set up before the constructor body runs. #privatefields are a good fit for plain helper classes you write; in component classes, state normally lives in regular fields so the template and decorators can see it.
Getters: computed properties
A getter runs every time it's read. In a component, the template reads it on every render, so the result is always up to date with the fields it uses:
// cartSummary.js
import { LightningElement } from 'lwc';
export default class CartSummary extends LightningElement {
items = [
{ id: 1, name: 'Keyboard', price: 2500, qty: 2 },
{ id: 2, name: 'Mouse', price: 900, qty: 1 },
];
couponPercent = 0;
get subtotal() {
return this.items.reduce((sum, i) => sum + i.price * i.qty, 0);
}
get total() {
return this.subtotal * (1 - this.couponPercent / 100); // getters can use other getters
}
get hasDiscount() {
return this.couponPercent > 0;
}
applyCoupon() {
this.couponPercent = 10; // one field changes → all getters update
}
}
<!-- cartSummary.html -->
<template>
<p>Subtotal: {subtotal}</p>
<template lwc:if={hasDiscount}><p>Coupon: {couponPercent}% off</p></template>
<p>Total: {total}</p>
<lightning-button label="Apply coupon" onclick={applyCoupon}></lightning-button>
</template>
Subtotal: 5900 Total: 5900 [Apply coupon] › click “Apply coupon” Subtotal: 5900 Coupon: 10% off Total: 5310 [Apply coupon]
Keep getters fast and side-effect free
Getters can run many times per render. Never call Apex, set fields or dispatch events inside one. If a calculation is expensive (sorting thousands of rows), compute it once when the data changes and store it in a field.
@api getter and setter pairs
A plain @api property just stores what the parent passes. When you need to react to the value – normalise it, validate it, derive other fields – use a getter/setter pair and put @api on the getter. The setter runs every time the parent assigns a new value:
// statusPill.js
import { LightningElement, api } from 'lwc';
const LABELS = { new: 'New', in_progress: 'In progress', done: 'Done' };
export default class StatusPill extends LightningElement {
_status = 'new';
history = [];
@api
get status() {
return this._status;
}
set status(value) {
const next = String(value ?? 'new').trim().toLowerCase().replaceAll(' ', '_');
if (next !== this._status) this.history = [...this.history, `${this._status} → ${next}`];
this._status = LABELS[next] ? next : 'new';
}
get label() {
return LABELS[this._status];
}
get historyText() {
return this.history.length ? this.history.join(', ') : 'no changes yet';
}
}
<!-- statusPill.html -->
<template>
<p>Status: {label}</p>
<p>History: {historyText}</p>
</template>
Status: New History: no changes yet › parent sets status = "In Progress" Status: In progress History: new → in_progress › parent sets status = "DONE" Status: Done History: new → in_progress, in_progress → done
- Store the value in a private-by-convention field (
_status) – the getter returns it. - Put
@apion the getter only, never on both. - The setter can run before the component is connected, so don't touch the DOM in it.
Inheritance and super
extends creates a subclass; super calls the parent's constructor or methods. Every component extends LightningElement, which is why the constructor must call super() first.
class BaseValidator {
constructor(label) {
this.label = label;
}
validate(value) {
return value == null || value === '' ? `${this.label} is required` : null;
}
}
class EmailValidator extends BaseValidator {
validate(value) {
const required = super.validate(value); // reuse the parent's check
if (required) return required;
return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value) ? null : `${this.label} is not a valid email`;
}
}
const email = new EmailValidator('Work email');
console.log(email.validate(''));
console.log(email.validate('asha@acme'));
console.log(email.validate('asha@acme.com'));
Work email is required Work email is not a valid email null
Mixins: what NavigationMixin really is
JavaScript classes have one parent. A mixin is a function that takes a class and returns a new class extending it with extra behaviour – so you can stack features. That's exactly what export default class extends NavigationMixin(LightningElement) does.
class LightningElementLike {
connectedCallback() {
console.log('base connected');
}
}
// a mixin: class in, class out
const WithLogging = (Base) => class extends Base {
log(message) {
console.log(`[${this.constructor.name}] ${message}`);
}
};
const WithRefresh = (Base) => class extends Base {
refresh() {
this.log?.('refreshing data');
}
};
class AccountPanel extends WithRefresh(WithLogging(LightningElementLike)) {
connectedCallback() {
super.connectedCallback();
this.refresh();
}
}
new AccountPanel().connectedCallback();
base connected [AccountPanel] refreshing data
The platform's mixins work the same way: NavigationMixin(LightningElement) returns a class with a [NavigationMixin.Navigate] method added. Mixins are powerful but easy to overuse; for sharing plain logic, a module of functions is usually simpler.
Practice
Try it yourself
A child component receives
@api recordIdsas a comma-separated string, but you want an array internally. How do you do that?Show answer
Use a getter/setter pair:
@api get recordIds() { return this._ids.join(','); } set recordIds(v) { this._ids = (v ?? '').split(',').map((s) => s.trim()).filter(Boolean); }Your getter
sortedRowssorts 5,000 rows and the page feels slow. What would you change?Show answer
Sort once when the data or the sort order changes (in the wire handler and the sort handler) and store the result in a field; the template then reads the field.
Quick check
Where does @api go in a getter/setter pair?
On the getter only.
What must a component constructor do first?
Call super().
What is a mixin?
A function that takes a class and returns a subclass with extra behaviour.
Summary
- Classes give you fields, methods, static members and private #fields.
- Getters are LWC's computed properties – keep them fast and pure.
- Use @api getter/setter pairs to react to values from the parent.
- extends and super share behaviour; mixins stack it.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.