How this Works

this depends on how a function is called, not where it is written. Lose it by taking the method out of its object, then fix it with bind.

JavaScript · beginner · 7 min · 12 steps · free

What you'll learn

This.js

const timer = {
  name: 'tea',
  seconds: 3,
  describe() {
    return `${this.name}: ${this.seconds}s`;
  },
};

console.log(timer.describe());
const detached = timer.describe;
try {
  detached();
} catch (err) {
  console.log('lost this:', err.message);
}
const bound = timer.describe.bind(timer);
console.log(bound());

Step by step

  1. timer is created and points to a new Object: {name: "tea", seconds: 3, describe: function describe()}.
  2. timer.describe(): the object before the dot is timer, so this = timer.
  3. describe returns "tea: 3s".
  4. describe() has finished, so its variables are gone. It prints tea: 3s.
  5. detached gets the same function, but taken out of the object.
  6. detached() is called with nothing before the dot, so this is undefined.
  7. Something in the try block threw TypeError: “Cannot read properties of undefined (reading 'name')”. JavaScript skips the rest of try and jumps to catch, with err holding the error.
  8. It prints lost this: Cannot read properties of undefined (reading 'name').
  9. bind(timer) makes a new function whose this is always timer.
  10. JavaScript calls describe(). It gets its own variables.
  11. describe returns "tea: 3s".
  12. The bound function works: "tea: 3s".

Common mistakes

Best practices

Key takeaways

Check yourself

const f = obj.m; f() — this?

Answer: undefined

obj.m.bind(obj)() — this?

Answer: obj

·

More in Objects and Arrays