← JavaScript

Intermediate · 5 of 17 · 18 min read

this in objects

The four rules that decide what this is, why a detached method loses it, and what arrow functions actually do differently.

  • this

this is decided when the function is called, not where it is written. For a normal function there is exactly one question that matters: what is to the left of the dot at the call site?

The four rules, in priority order

Call looks like this is
new Fn() the brand-new object
fn.call(obj), fn.apply(obj), fn.bind(obj)() obj
obj.fn() obj — whatever is left of the dot
fn() undefined (strict) or globalThis (sloppy)
function who() {
  return this;
}

const obj = { who };

console.log(obj.who() === obj);        // true  — method call
console.log(who.call(obj) === obj);    // true  — explicit
console.log(new who() instanceof who); // true  — construction
console.log(who());                    // undefined in a module

Arrow functions are not on that list, because they do not have their own this at all.

The method call

Inside a method, this is the object the method was reached through — which is how a method reads its own object’s other properties:

const user = {
  first: 'Ana',
  last: 'Díaz',
  fullName() {
    return `${this.first} ${this.last}`;
  },
};

console.log(user.fullName()); // "Ana Díaz"

Only the last link of the chain counts. Depth does not matter:

const app = {
  name: 'outer',
  child: {
    name: 'inner',
    report() { return this.name; },
  },
};

console.log(app.child.report()); // "inner" — `app.child` is left of the dot

Losing the receiver

This is the bug, and it is the same bug every time: the function is separated from its object.

const user = {
  name: 'Ana',
  greet() { return `Hi, ${this.name}`; },
};

const detached = user.greet;
// console.log(detached()); // TypeError: Cannot read properties of undefined

Nothing was passed, so this is undefined and reading .name throws. The same thing happens any time you hand the method to something that will call it later:

const user = {
  name: 'Ana',
  greet() { return `Hi, ${this.name}`; },
};

// setTimeout(user.greet, 0);        // `this` is lost
// [1].forEach(user.greet);          // `this` is lost
// element.addEventListener('click', user.greet); // `this` is the element

setTimeout(() => user.greet(), 0);   // fix 1: call it through the object
setTimeout(user.greet.bind(user), 0); // fix 2: bind the receiver

A function passed as a value carries no memory of where it came from. user.greet evaluates to the plain function, and the connection to user only exists in the user.greet() syntax.

The nested-function trap

A plain function declared inside a method does not inherit the method’s this:

const counter = {
  count: 3,
  report() {
    console.log('outer', this.count); // outer 3

    function inner() {
      console.log('inner', this?.count); // inner undefined
    }
    inner(); // a plain call — rule 4 applies
  },
};

counter.report();

inner() is a plain call, so its this is undefined regardless of where it was written. Before arrow functions, the workaround was to save the value:

const counter = {
  count: 3,
  report() {
    const self = this; // the `var self = this` you will see in older code
    function inner() {
      console.log(self.count); // 3
    }
    inner();
  },
};
counter.report();

Now it is simply an arrow:

const counter = {
  count: 3,
  report() {
    const inner = () => console.log(this.count); // `this` comes from report()
    inner(); // 3
  },
};
counter.report();

Arrow functions

An arrow function has no this of its own. A this inside one resolves exactly like any other variable: by looking outwards through the enclosing scopes. That makes it immune to the call site — and useless as a method.

const bad = {
  name: 'Ana',
  greet: () => `Hi, ${this?.name}`, // `this` is the module scope, not `bad`
};
console.log(bad.greet()); // "Hi, undefined"

const good = {
  name: 'Ana',
  greet() { return `Hi, ${this.name}`; }, // method shorthand
};
console.log(good.greet()); // "Hi, Ana"

Where the arrow is right is inside a method, for a callback:

const cart = {
  tax: 0.21,
  items: [100, 200],
  withTax() {
    return this.items.map((price) => price * (1 + this.tax)); // `this` still the cart
  },
  withTaxBroken() {
    return this.items.map(function (price) {
      return price * (1 + this.tax); // `this` is undefined here
    });
  },
};

console.log(cart.withTax()); // [121, 242]
Normal function Arrow function
this the call site decides the surrounding scope
call / apply / bind can change it yes no
arguments has its own the enclosing one
usable with new yes no — TypeError
good as an object method yes no
good as a callback inside a method no yes
const arrow = () => this;
const normal = function () { return this; };
const target = { id: 1 };

console.log(normal.call(target).id); // 1
console.log(arrow.call(target));     // the enclosing `this` — bind had no effect
// new arrow();                      // TypeError: arrow is not a constructor

Most array callbacks also accept a thisArg as their last argument, which predates arrows and still works:

const cart = { tax: 0.21 };
console.log([100].map(function (p) { return p * (1 + this.tax); }, cart)); // [121]

this in classes

Class methods are normal functions on the prototype, so they lose this the same way — which is why React class components needed bind in the constructor:

class Counter {
  count = 0;

  increment() {
    this.count += 1;
    return this.count;
  }

  // a class field holding an arrow: `this` is captured per instance
  incrementSafe = () => {
    this.count += 1;
    return this.count;
  };
}

const c = new Counter();
const loose = c.increment;
// loose();              // TypeError — detached
const safe = c.incrementSafe;
console.log(safe());     // 1 — works anywhere

The trade-off of the arrow field is real: it is a new function object per instance, stored on the instance rather than shared on the prototype. For a handful of handlers that is fine; for a class instantiated thousands of times it is not.

this at the top level

// In an ES module:
console.log(this); // undefined

// In a CommonJS file:
// console.log(this); // module.exports, i.e. {}

// In a plain <script>:
// console.log(this); // window

Use globalThis when you actually want the global object — it is the one spelling that works in a browser, in Node and in a worker.

Common mistakes

An arrow function as an object method

Mistake. const o = { n: 1, get: () => this.n }. Why it fails. The arrow captured the surrounding scope’s this, which at module level is undefined. The object is never consulted. What to do instead. Method shorthand: get() { return this.n }.

Passing a method as a callback

Mistake. promise.then(this.handleData) or setTimeout(obj.tick, 100). Why it fails. Only the function value is passed; the receiver is dropped at the call site later. What to do instead. promise.then((d) => this.handleData(d)), or bind once in the constructor.

Reaching for bind inside render

Mistake. onClick={this.handle.bind(this)} in a function that re-runs often. Why it fails. bind returns a new function every call, so the prop changes identity on every render and defeats memoisation. What to do instead. Bind once — in the constructor, or as a class field arrow — so the identity is stable.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

A method is just a function stored on an object — and storing it somewhere else changes something.

This worked as user.greet(). Why does it break once it is pulled into a variable? (module code, so strict mode)

Code sample
const user = {
  name: "Gabriel",
  greet() {
    console.log(this.name);
  },
};

const greet = user.greet;
greet(); // TypeError

For a regular (non-arrow) function, what decides the value of this?

Why is an arrow function a poor choice for an object *method*?

Practise this →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.