Methods and this

Topic 2 of 5 in Objects7 min readBeginnerFree course

Overview

A function stored on an object is called a method. Methods give objects behaviour to go with their data. Inside a method, this refers to the object you called it on.

JavaScript
const learner = {
  name: 'Asha',
  greet() {
    return `Hi, I’m ${this.name}`;
  },
};

learner.greet(); // 'Hi, I’m Asha'

You’ve been using methods all along: console.log, 'text'.toUpperCase(), Math.max and array.push are all methods.

Writing methods

There are three ways to put a function on an object. The first — method shorthand — is the one to use:

JavaScript
const calculator = {
  // 1. method shorthand (recommended)
  add(a, b) {
    return a + b;
  },
  // 2. a function expression as a property value
  subtract: function (a, b) {
    return a - b;
  },
  // 3. an arrow function — fine only if it doesn't need `this`
  multiply: (a, b) => a * b,
};

Why this?

A method could refer to its object by name — learner.name — but that breaks as soon as the object is renamed or copied. this always means “whichever object this method was called on”, so the same method works for many objects:

JavaScript
function describe() {
  return `${this.title} has ${this.chapters} chapters`;
}

const js = { title: 'JavaScript', chapters: 14, describe };
const sql = { title: 'SQL', chapters: 6, describe };

js.describe();  // 'JavaScript has 14 chapters'
sql.describe(); // 'SQL has 6 chapters'

One function, two objects, two different this values. Classes (later in the course) are built on exactly this idea.

this is decided by the call

this isn’t fixed when you write the method — it depends on how the function is called. The rule of thumb: look at what’s to the left of the dot at the moment of the call.

Four calls. learner.greet() has learner before the dot, so this is learner. Storing the method in g and calling g() has no object before the dot, so this is undefined and it throws. Passing learner.greet to setTimeout passes only the function, so this is lost. Wrapping it as () => learner.greet() calls it with the dot, so it works.

Take the method off the object and it loses its this:

JavaScript
const greet = learner.greet;
greet(); // TypeError in strict mode — this is undefined

This often happens when passing a method as a callback, for example to setTimeout or addEventListener — the function is handed over on its own, without the object.

Summary of the rules

How the function is called this is
obj.method() obj
fn() (plain call) undefined in strict mode and modules (the global object in old sloppy scripts)
new Thing() the brand-new object
fn.call(obj, …) / fn.apply(obj, […]) obj
fn.bind(obj) then call obj, permanently
Arrow function whatever this was where the arrow was written
DOM event handler (regular function) the element the listener is on

Fixing a lost this

Use bind to create a copy with this locked in, or wrap the call in an arrow function:

JavaScript
setTimeout(learner.greet.bind(learner), 100);
setTimeout(() => learner.greet(), 100);

The arrow-function wrapper is usually clearer: it calls learner.greet() with the dot, just as you’d write it normally.

call and apply

call and apply run a function immediately with a chosen this. They differ only in how arguments are passed:

JavaScript
function introduce(greeting, punctuation) {
  return `${greeting}, I'm ${this.name}${punctuation}`;
}

introduce.call(learner, 'Hello', '!');    // "Hello, I'm Asha!"
introduce.apply(learner, ['Hello', '!']); // same, arguments as an array

You’ll rarely need these in everyday code, but you’ll see them in libraries.

Arrow functions and this

Arrow functions borrow this from the surrounding code. That’s great for callbacks inside methods, but wrong for the methods themselves:

JavaScript
const bad = {
  name: 'Ravi',
  greet: () => `Hi, ${this.name}`, // this is not `bad`
};

Here’s where arrows shine — a callback inside a method keeps the method’s this:

JavaScript
const team = {
  name: 'Blue',
  members: ['Asha', 'Ravi'],
  list() {
    return this.members.map((m) => `${m} (${this.name})`);
  },
};

team.list(); // ['Asha (Blue)', 'Ravi (Blue)']

With a regular function callback, the inner this would be undefined and this.name would throw.

Rule of thumb: use the short method syntax (greet() {}) for methods, and arrow functions for callbacks inside them.

Chaining methods

If a method returns this, you can call another method straight after it. This style is called a fluent interface:

JavaScript
const order = {
  items: [],
  add(item) {
    this.items.push(item);
    return this;
  },
  clear() {
    this.items = [];
    return this;
  },
};

order.add('tea').add('cake').add('coffee');
order.items; // ['tea', 'cake', 'coffee']

Many libraries use this pattern, and so do built-ins: ' Hi '.trim().toLowerCase() chains because each string method returns a new string.

Getters and setters

A getter looks like a property but runs a function when read; a setter runs when the property is assigned:

JavaScript
const person = {
  first: 'Asha',
  last: 'Rao',
  get fullName() {
    return `${this.first} ${this.last}`;
  },
  set fullName(value) {
    [this.first, this.last] = value.split(' ');
  },
};

person.fullName;              // 'Asha Rao' — no brackets
person.fullName = 'Ravi Kumar';
person.first;                 // 'Ravi'

Use getters for values that are calculated from other properties, so they can never get out of date.

Exercise

A tiny counter object

Give counter an increment() method that adds 1 to count and returns the new value, and a reset() method that sets count back to 0. Make increment return this instead, so calls can be chained: counter.increment().increment().

JavaScript
const counter = {
  count: 0,
  // add increment and reset here
};

Summary

  • A method is a function stored on an object; write it with the short name() {} syntax.
  • this is the object the method was called on — decided at call time, by what’s left of the dot.
  • Detaching a method (assigning it or passing it as a callback) loses its this.
  • Fix a lost this with bind or by wrapping the call in an arrow function.
  • Arrow functions don’t have their own this; avoid them for methods, use them for callbacks inside methods.