this, Classes & Composition
Predict what this refers to, use bind and arrow functions deliberately, and design objects with classes or composition.
By the end, you’ll be able to…
- Explain how the call site determines this for a regular function.
- Use call, apply, and bind and choose between arrow functions and methods.
- Write classes with instance fields, private fields, getters, and static members.
- Prefer composition over inheritance when a hierarchy does not fit.
01this is decided at the call site
The value of this is decided when a function is called, not when it is defined. Calling user.greet() sets this to user because the call appears as a property access. Calling the same function as a standalone greet() sets this to undefined in strict mode, which includes modules. A callback passed to setTimeout loses its receiver for the same reason. Reading this as the current receiver helps predict these outcomes.
call and apply invoke a function immediately with a chosen this; call takes arguments separately, while apply takes an array. bind returns a new function with this permanently fixed and does not call it. Use bind when a method will be passed somewhere that will not preserve the receiver, such as an event listener or a promise callback.
02Arrow functions and regular methods
Arrow functions do not have their own this. They read this from the surrounding scope, which is why an arrow inside a method still sees the instance. That makes arrows excellent for callbacks such as array map functions or timer handlers inside a method. It also makes them unsuitable as object methods: an arrow used as user.greet would ignore user entirely.
Regular methods are the right choice when the function needs its own receiver. A class field arrow, such as handleClick = () => {}, binds the instance automatically but creates a function per instance. bind produces a similar fixed receiver without changing the class definition. Prefer the plainest option that preserves the behaviour you need, and avoid binding functions that never lose their receiver.
03Classes, fields, and privacy
A class defines a template for objects with shared methods. The constructor initialises each instance, instance fields declare per-object state, and methods live on the prototype. Private fields start with # and are enforced by the language: code outside the class cannot read or write them. Static members belong to the class itself, which suits constants or factories that do not need an instance.
Getters expose computed values while keeping storage private. Validation in a method or setter protects an invariant, such as a balance never becoming negative. Use privacy for state that must not be corrupted, not for every value. A class is most useful when identity, behaviour, and invariants belong together; for a bag of data passed between functions, a plain object is simpler.
04Composition over deep inheritance
Inheritance expresses an is-a relationship: a SavingsAccount is a BankAccount. It works when the child truly extends the parent's contract, but deep chains become fragile. Changing a parent method can break children in surprising ways, and a child inherits everything whether it needs it or not. Prefer shallow hierarchies and keep shared behaviour in small functions or components.
Composition expresses has-a or uses-a. Instead of extending a logger, a class can accept one; instead of inheriting formatting, a function can apply it. Composition lets you combine capabilities without naming a single parent. Many beginner designs become clearer as a data object plus a handful of functions. Choose inheritance only when the relationship is stable and the shared contract is genuinely the same.
The ideas worth keeping.
- this depends on the call site; use bind or an arrow to preserve the receiver you need.
- Classes suit state with invariants, while composition combines capabilities without fragile inheritance chains.
- Private fields protect internal state and static members belong to the class rather than an instance.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Fix a detached method
Create a counter object with a count property and an increment method that uses this. Then create a separate function named increment that can be called on its own but still updates the original counter. Call it twice and log the counter's count, and explain why a detached method needs binding.
Explore a worked solution
const counter = { count: 0, increment() { this.count += 1; return this.count; }};const increment = counter.increment.bind(counter);console.log(increment());console.log(increment());console.log(counter.count);A detached method loses its receiver, so this would be undefined in a module. bind creates a new function whose this is permanently counter, and both calls update the same object.
Exercise 2: A temperature value object
Write a Temperature class with a private #celsius field. The constructor rejects non-finite values with a TypeError. Add a fahrenheit getter and a static fromFahrenheit(value) factory that returns a Temperature. Create one from 212 Fahrenheit and log its fahrenheit value.
Explore a worked solution
class Temperature { #celsius; constructor(celsius) { if (!Number.isFinite(celsius)) { throw new TypeError("Celsius must be a number"); } this.#celsius = celsius; } get fahrenheit() { return (this.#celsius * 9) / 5 + 32; } static fromFahrenheit(value) { return new Temperature(((value - 32) * 5) / 9); }}const boiling = Temperature.fromFahrenheit(212);console.log(boiling.fahrenheit);The private field can only be set through the constructor, and the getter computes a derived value without exposing storage. The static factory converts the input and delegates to the constructor's validation.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: Fix a detached method
Create a counter object with a count property and an increment method that uses this. Then create a separate function named increment that can be called on its own but still updates the original counter. Call it twice and log the counter's count, and explain why a detached method needs binding.
1 2 2
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.