Sub topic 3
Adding Behavior with Instance Methods
This chapter assumes you can write a class with a constructor and create instances with new, as covered in the previous chapters. You should also know arrow functions, template literals, and the basic idea that this refers to the object a function was called on.
A constructor gives each instance its data. Instance methods give instances behavior: functions that read and change that data. This chapter covers how to define methods, how they reach the instance's data through this, the different kinds of methods a class body accepts, and the mistakes that show up most often.
Defining a Method
An instance method is a function written directly in the class body, with no function keyword and no commas between members:
class Temperature {
constructor(celsius) {
this.celsius = celsius;
}
toFahrenheit() {
return this.celsius * 9 / 5 + 32;
}
isFreezing() {
return this.celsius <= 0;
}
describe() {
const note = this.isFreezing() ? ', freezing' : '';
return `${this.celsius}°C (${this.toFahrenheit()}°F)${note}`;
}
}
const t = new Temperature(-5);
console.log(t.toFahrenheit()); // 23
console.log(t.describe()); // '-5°C (23°F), freezing'The method shapes to notice in this example:
- Reading state.
toFahrenheitreadsthis.celsius. Inside a method called ast.toFahrenheit(),thisist. - Calling other methods.
describecallsthis.isFreezing()andthis.toFahrenheit(). A method has to go throughthisto reach a sibling method. A bareisFreezing()would look for a variable in scope and fail. - Returning values. Methods are ordinary functions and can return anything, or nothing.
One Function, Shared by Every Instance
A method is not copied onto each instance. The class stores it once, and every instance finds that same function when you call it:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
distanceTo(other) {
return Math.hypot(this.x - other.x, this.y - other.y);
}
}
const a = new Point(0, 0);
const b = new Point(3, 4);
console.log(a.distanceTo(b)); // 5
console.log(a.distanceTo === b.distanceTo); // true
console.log(Object.keys(a)); // [ 'x', 'y' ]Object.keys(a) lists only x and y. The instance holds the data, and the method lives on a shared object behind it. When you write a.distanceTo, JavaScript doesn't find the property on a, so it looks at the shared object and finds it there. The chapter "What Classes Really Are: Functions and Prototypes" explains that shared object in detail. For now, you only need the lookup order.
The diagram points to two practical facts:
- Memory. A thousand
Pointinstances share onedistanceTofunction. If you assignedthis.distanceTo = function () { ... }in the constructor, you would create a thousand separate functions. - Shadowing. An own property with the same name as a method wins the lookup and hides the method. That causes a common bug, shown later in this chapter.
Returning this for Method Chaining
If a method changes the instance and returns this, callers can chain calls together. Builders and fluent APIs are written this way:
class QueryBuilder {
constructor(table) {
this.table = table;
this.conditions = [];
this.limitCount = null;
}
where(condition) {
this.conditions.push(condition);
return this;
}
limit(n) {
this.limitCount = n;
return this;
}
build() {
let sql = `SELECT * FROM ${this.table}`;
if (this.conditions.length > 0) {
sql += ` WHERE ${this.conditions.join(' AND ')}`;
}
if (this.limitCount !== null) {
sql += ` LIMIT ${this.limitCount}`;
}
return sql;
}
}
const sql = new QueryBuilder('users')
.where('age > 18')
.where("country = 'NZ'")
.limit(10)
.build();
console.log(sql);
// SELECT * FROM users WHERE age > 18 AND country = 'NZ' LIMIT 10Each chained call works only because the previous method returned the instance. If you forget return this in one method, that method returns undefined, and the next call in the chain throws TypeError: Cannot read properties of undefined.
Other Kinds of Methods
The class body accepts more than plain method names. The forms below work for instance methods as well:
const summaryName = 'describe';
class Playlist {
constructor(...songs) {
this.songs = songs;
}
// Computed name: the method is called "describe"
[summaryName]() {
return `${this.songs.length} songs`;
}
// Generator method under a symbol key: makes instances iterable
*[Symbol.iterator]() {
yield* this.songs;
}
// Async method: always returns a Promise
async loadLyrics(index) {
const song = this.songs[index];
await new Promise((resolve) => setTimeout(resolve, 10));
return `Lyrics for ${song}`;
}
}
const list = new Playlist('Intro', 'Verse', 'Chorus');
console.log(list.describe()); // '3 songs'
console.log([...list]); // [ 'Intro', 'Verse', 'Chorus' ]
list.loadLyrics(1).then((text) => console.log(text)); // 'Lyrics for Verse'| Form | Syntax | Typical use |
|---|---|---|
| Plain method | `name() {}` | Most behavior |
| Computed name | `[expr]() {}` | Names from variables or symbols |
| Generator | `*name() {}` | Lazy sequences, custom iteration |
| Async | `async name() {}` | Methods that await I/O |
| Async generator | `async *name() {}` | Streams of async values |
Implementing [Symbol.iterator] is the standard way to make your own collection work with for...of, spread syntax, and destructuring.
How Methods Differ from Ordinary Properties
Methods defined in a class body behave differently from functions you attach yourself.
They are non-enumerable. They do not show up in Object.keys, for...in, or object spread, and JSON.stringify ignores them. That is why { ...point } copies only the data.
They are not constructors. Class methods cannot be called with new:
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
distanceTo(other) {
return Math.hypot(this.x - other.x, this.y - other.y);
}
}
const p = new Point(1, 2);
console.log(p.distanceTo.prototype); // undefined
try {
new p.distanceTo(p);
} catch (err) {
console.log(err.constructor.name, err.message);
// TypeError p.distanceTo is not a constructor
}They run in strict mode, as all class code does. This matters most when a method is called without an object in front of it. The chapter "How Classes Differ from Functions" covers strict mode.
Common Errors
Forgetting this
class Counter {
constructor() {
this.count = 0;
}
increment() {
count++; // ReferenceError: count is not defined
}
}Instance data is never in scope as a bare variable. Write this.count++. If a variable called count happens to exist in an outer scope, the method silently changes that variable instead, which is harder to spot than the error.
Object-literal habits in the class body
Writing function before a method name, or putting commas between methods, is a SyntaxError:
// Both are syntax errors inside a class body:
// function toFahrenheit() { ... }
// toFahrenheit() { ... },Semicolons between members are allowed but unnecessary.
Duplicate method names
If two methods have the same name, the later one silently replaces the earlier one. No error is raised. A linter rule such as ESLint's no-dupe-class-members catches this.
An instance property shadowing a method
class Report {
constructor(title) {
this.title = title;
this.print = false; // meant to be a flag, but reuses the method's name
}
print() {
return `Report: ${this.title}`;
}
}
const r = new Report('Q3');
console.log(typeof r.print); // 'boolean'
// r.print(); // TypeError: r.print is not a functionThe own property print wins the lookup shown in the diagram, so the method can no longer be reached through r. Use different names for data and behavior, such as shouldPrint and print().
Detaching a method from its instance
If you pass t.describe as a callback, for example to setTimeout or an event listener, the function is called without t in front of it, and this is undefined. The chapter "Keeping this Bound When Methods Become Callbacks" covers the fixes. For now, remember that this depends on how a method is called, not on where it was defined.
Exercise
Add a method warmBy(degrees) to the Temperature class that increases celsius and supports chaining, so that new Temperature(-5).warmBy(3).warmBy(4).describe() returns '2°C (35.6°F)'. What must the method return, and why does the chain fail without it?
Show answer
The method is warmBy(degrees) { this.celsius += degrees; return this; }. It must return this, the instance, so the next .warmBy or .describe call has an object to run on. Without the return, warmBy returns undefined, and the next call throws a TypeError (Cannot read properties of undefined).
Exercise
Given class Box { constructor() { this.size = 1; this.open = true; } open() { return 'opened'; } }, what does new Box().open() do, and how would you fix it?
Show answer
It throws TypeError: ... open is not a function. The constructor creates an own property open with the value true. Own properties are found before shared class methods, so the boolean hides the method. Rename one of them, for example store the state as this.isOpen = true and keep the open() method.
Exercise
You create 10,000 instances of a class with one method defined in the class body. How many function objects exist for that method, and would Object.keys(instance) include the method's name?
Show answer
There is one function object, shared by all 10,000 instances, because class methods are stored once rather than copied to each instance. Object.keys(instance) does not include it, because the method is not an own property of the instance and class methods are non-enumerable.