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.
Welcome back!
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, sothisisenemy.const f = enemy.move; f();: called as a plain function, sothisisundefined(class bodies run in strict mode), andthis.xthrows 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 permanentlyArrow 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); // 1Static 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.maxis 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
| Aspect | Instance member | Static member |
|---|---|---|
| Belongs to | Each object separately | The class as a whole |
| Reached through | enemy.health, enemy.move() | Enemy.count, Enemy.fromSave() |
| Has a this instance? | Yes | No: pass an object in if needed |
| Good for | Per-object state and behavior | Constants, factories, utilities |
| Watch out | Lost this in callbacks | Mutable 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 100The 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.
new Counter().increment().increment().countCounter.fromValue(5).countCounter.fromValue(5).increment().countnew Counter().count
Step 9 of 14Tap to reveal
Three ways "this" can surprise you in JavaScript
Detached methods
Storing
obj.methodin a variable or passing it as a callback separates it from the object. When it runs later,thisis undefined. Wrap it in an arrow function or usebind.Regular functions inside methods
A classic
function () {}written inside a method gets its ownthis. Insidearray.forEach(function (x) { this.total += x; }),thisis not your object. Use an arrow function instead.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
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?
Lesson complete!