🎓 A1Learner
🔍
0 of 50 lessons completed

JavaScript How this Is Decided

The value of this is decided by how a function is called. The same function can see a different this at each call site.

A method call sets this

The call has user before the dot. Inside greet, this points at user, so this.name reads Ana.

const user = {
  name: "Ana",
  greet: function () {
    console.log("Hello, " + this.name);
  }
};
user.greet();

A plain call changes this

The call has no object before the dot. In a classic script, this becomes the global object, so the check prints true.

function show() {
  console.log(this === globalThis);
}
show();

A detached method loses its object

The method is stored in a plain variable and called with no dot. This no longer points at user, so this.city reads as undefined.

const user = {
  name: "Ana",
  city: "Portland",
  showCity: function () {
    console.log(this.city);
  }
};
const f = user.showCity;
f();

An arrow function keeps the outer this

The arrow function sits inside the greet method. It keeps the this of that method, so it reads the name from user.

const user = {
  name: "Ana",
  greet: function () {
    const arrow = () => this.name;
    console.log(arrow());
  }
};
user.greet();

Example

const counter = {
  count: 3,
  read: function () {
    console.log(this.count);
  }
};
counter.read();
const readIt = counter.read;
readIt();

Key points

  • this: a keyword that points at the object tied to the current call
  • A method call sets this to the object before the dot.
  • A plain call sets this to the global object in a classic script.
  • A detached method loses its object, so this stops pointing at it.
  • An arrow function keeps the this from the code around it.

In this example, the method call reads count from the counter object. The detached call runs the same function with no object before the dot, so this no longer points at the counter and count reads as undefined.

Note

A plain function reads this fresh at each call.

Try it Yourself

Edit the code, then press Run.

Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

In user.greet(), what does this point at inside greet?