Find a course

Module 1: Thinking in ObjectsLesson 3 of 1213 min

Methods, this and Static Members

Learn how this is bound when a method runs, avoid the lost-this bug in callbacks, and use static members for data that belongs to the class itself.

Step 1 of 14Learn

What "this" really points at

Inside a method, this is not fixed when you write the class. In JavaScript it is decided at call time, by how the method is called:

  • enemy.move(): called through an object, so this is enemy.
  • const f = enemy.move; f();: called as a plain function, so this is undefined (class bodies run in strict mode), and this.x throws a TypeError.

That second case is the famous lost this bug, and it usually sneaks in through callbacks:

class Timer {
  constructor() { this.seconds = 0; }
  tick() { this.seconds++; }
  start() { setInterval(this.tick, 1000); }   // bug: tick loses its object
}

setInterval receives the bare function tick and later calls it without any object, so this isn't the timer anymore.

Two standard fixes:

start() { setInterval(() => this.tick(), 1000); }   // arrow function keeps outer this
start() { setInterval(this.tick.bind(this), 1000); } // bind fixes this permanently

Arrow functions don't have their own this; they use the this of the code around them, which here is the timer. Python avoids this particular trap: timer.tick produces a bound method that remembers its object, so passing it as a callback just works.

Step 2 of 14Practice · Choose one

A button handler is registered with button.addEventListener('click', this.save) inside a class method. When the button is clicked, save throws "Cannot read properties of undefined". What is the best fix?

Step 3 of 14Learn

Instance members vs. static members

Most fields and methods belong to instances: each enemy has its own health. Some things belong to the class as a whole. Those are static members.

class Enemy {
  static count = 0;                 // one value shared by the class
  static MAX_HEALTH = 100;

  constructor(x, y) {
    this.x = x; this.y = y;
    this.health = Enemy.MAX_HEALTH;
    Enemy.count++;                  // reached through the class name
  }

  static fromSave(data) {           // a static "factory" helper
    return new Enemy(data.x, data.y);
  }
}

const e = Enemy.fromSave({ x: 3, y: 4 });
console.log(Enemy.count);   // 1

Static members are accessed through the class (Enemy.count), not through an instance. A static method has no this instance to work with, so it can't read health or x unless you pass it an object.

Good uses of static members:

  • Constants that every instance shares: Enemy.MAX_HEALTH, Color.RED.
  • Factory methods that build instances in a named way: Date.now(), Enemy.fromSave(data), Python's @classmethod.
  • Utility functions closely tied to the class: Math.max is entirely static.

Be careful with static fields that change, such as a counter. They are shared global state in disguise, and shared mutable state makes testing harder: one test's enemies leak into the next test's count.

Step 4 of 14Practice · Sort into groups

Should each member be an instance member or a static member?

Tap an item, then tap its group (or drag it there).

Step 5 of 14Compare

Instance members vs static members

AspectInstance memberStatic member
Belongs toEach object separatelyThe class as a whole
Reached throughenemy.health, enemy.move()Enemy.count, Enemy.fromSave()
Has a this instance?YesNo: pass an object in if needed
Good forPer-object state and behaviorConstants, factories, utilities
Watch outLost this in callbacksMutable static fields are hidden global state

Step 6 of 14Learn

Getters, setters and computed properties

Sometimes a value is better computed than stored. A rectangle doesn't need an area field that could fall out of sync with width and height; it can compute area on demand. JavaScript lets you write that as a getter, read like a field but run like a method:

class Temperature {
  constructor(celsius) { this.celsius = celsius; }
  get fahrenheit() { return this.celsius * 9 / 5 + 32; }
  set fahrenheit(f) { this.celsius = (f - 32) * 5 / 9; }
}
const t = new Temperature(20);
t.fahrenheit;        // 68  (no parentheses: it's a getter)
t.fahrenheit = 212;  // setter runs; t.celsius is now 100

The one stored value is celsius; Fahrenheit is always derived from it, so the two can never disagree. Python offers the same idea with the @property decorator, and C# has built-in properties.

Getters are perfect for cheap, derived values: a full name from first and last name, a total from line items, a boolean such as isEmpty. Avoid hiding slow work (a network call, a big calculation) behind a getter, because code that looks like a simple field read shouldn't take two seconds.

Setters are useful for validation: a setter can reject an invalid value before it is stored. You'll use that in the next module, where protecting an object's data is the whole point.

Step 7 of 14Practice · Work it out

Using the Temperature class above, a program runs const t = new Temperature(25); t.fahrenheit = 50;. What is the value of t.celsius afterwards? Round to one decimal place.

Step 8 of 14Practice · Code challenge

Write a class Counter with: a constructor that sets count to 0; a method increment() that adds 1 and returns the counter itself (so calls can be chained); and a static method fromValue(n) that returns a new Counter whose count is n.

Runs in a sandbox in your browser.
  • new Counter().increment().increment().count
  • Counter.fromValue(5).count
  • Counter.fromValue(5).increment().count
  • new Counter().count

Step 9 of 14Tap to reveal

Three ways "this" can surprise you in JavaScript

  1. Detached methods

    Storing obj.method in a variable or passing it as a callback separates it from the object. When it runs later, this is undefined. Wrap it in an arrow function or use bind.

  2. Regular functions inside methods

    A classic function () {} written inside a method gets its own this. Inside array.forEach(function (x) { this.total += x; }), this is not your object. Use an arrow function instead.

  3. Arrow functions as methods in object literals

    An arrow function never has its own this. Writing { count: 0, inc: () => this.count++ } doesn't refer to the object at all. Use normal method syntax for methods: inc() { this.count++; }.

Step 10 of 14Learn

Methods that return values vs. methods that change state

As your classes grow, it helps to sort methods into two kinds:

  • Queries answer a question and change nothing: cart.total(), enemy.isAlive(), account.balance. You can call them as often as you like without side effects.
  • Commands change the object's state: cart.addItem(item), enemy.takeDamage(10), account.withdraw(50).

A long-standing guideline called command-query separation says each method should be one or the other. A method named getTotal() that also quietly applies a discount and logs a message is a trap: a developer who calls it twice to display the total on two screens now applies the discount twice.

There are reasonable exceptions. array.pop() both removes and returns an item, and that's convenient. Chained methods like the increment() you wrote return this so calls can be strung together. But when you name a method get..., is... or has..., readers will assume it's a safe query, so keep it that way.

This also guides naming: queries read like nouns or yes/no questions (total, isEmpty), and commands read like verbs (add, remove, reset).

Step 11 of 14Practice · Sort into groups

Sort each method into query (answers a question, no changes) or command (changes state).

Tap an item, then tap its group (or drag it there).

Step 12 of 14Diagram

Command-query separation

Command-query separationHierarchy diagram: Public methods, Queries: answer, change nothing, Commands: change state, total, isEmpty, isAlive(), balance, addItem(), reset(), takeDamage(), withdraw().Public methodsQueries:answer, changenothingCommands:change statetotal, isEmptyisAlive(), balanceaddItem(), reset()takeDamage(),withdraw()

Tap a shape with to see more.

Public methods
Queries: answer, change nothing

Safe to call any number of times.

Commands: change state

Named with verbs; calling twice does it twice.

total, isEmpty
isAlive(), balance
addItem(), reset()
takeDamage(), withdraw()

Step 13 of 14Practice · True or false

A static method in JavaScript can read an instance's fields through this without being given the instance.

Step 14 of 14Practice · What would you do?

What would you do?

Priya's ShoppingCart class stores items and also a separate total field. Every method that adds or removes items is supposed to update total, but customers keep seeing totals that don't match their carts. What should she change?