What does "this" mean in JavaScript?

HTML, CSS & JS 2 min read
Short answer

In a regular function, this is determined at call time by what precedes the dot. Arrow functions have no this of their own and inherit it from the enclosing scope.

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

user.greet();                  // 'Hi, Dom' — called on user

const fn = user.greet;
fn();                          // 'Hi, undefined' — no object before the dot

The method did not change. The call did. That is the entire concept.

#The classic callback bug

javascript
button.addEventListener('click', user.greet);   // this is the button, not user

Fixes:

javascript
button.addEventListener('click', () => user.greet());
button.addEventListener('click', user.greet.bind(user));

#Arrow functions capture this

javascript
class Timer {
  constructor() {
    this.seconds = 0;
    setInterval(() => { this.seconds++; }, 1000);   // works
  }
}

With a regular function there, this would be the timer object or undefined. Arrow functions inherit this from where they were written, which is what you want in a callback.

#Which is why arrows are wrong for methods

javascript
const user = {
  name: 'Dom',
  greet: () => `Hi, ${this.name}`,     // this is NOT user
};

Defined at the top level of a module, this is undefined. Use shorthand method syntax for object methods.

#The rules, in priority order

  1. new Foo()this is the new object.
  2. fn.call(obj), fn.apply(obj), fn.bind(obj)this is obj.
  3. obj.fn()this is obj.
  4. Plain fn()undefined in strict mode and modules, globalThis otherwise.
  5. Arrow function — whatever this was where it was defined.