JavaScript path · Foundations · Topic 3 of 12

How this is decided

Not started

For ordinary functions, this is set by how the function is called: obj.method() gives obj, new gives the freshly created object, call/apply/bind set it explicitly, and a plain call gives undefined in strict code (classes and modules are always strict). Arrow functions have no this of their own; they use the one from the code around them.

Why it matters: It explains the "this is undefined" error when you pass a method around as a callback.

1

How it works

The explanation, with examples you can run.

Four ways to call a function

  1. With new: new User() creates an object and passes it as this.
  2. Explicitly: fn.call(x), fn.apply(x) and fn.bind(x) choose this yourself. A bound function keeps it for good.
  3. As a method: obj.fn() passes obj. It is the dot at the moment of the call that counts, not where the function was defined.
  4. Plainly: fn() passes undefined in strict code. In old sloppy-mode scripts it falls back to the global object, which hides the bug.
⌘/Ctrl + Enter
OutputNot run yet

Press Run to see what your code prints, in order.

Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.

Arrow functions

An arrow function does not get a this from its call. It uses the this of the code it sits in. That makes it the right choice for callbacks inside methods, and the wrong choice for a method itself: an arrow written as an object property sees the this of the surrounding code, not the object.

⌘/Ctrl + Enter
OutputNot run yet

Press Run to see what your code prints, in order.

Runs in this browser, in an isolated frame with no access to this page. console.log, info, warn and error are shown; code runs as a classic script, so use an async function for await.

2

Check yourself

2 questions. Get them all right to finish this topic.

  1. 1.In a module, `const f = obj.method; f()` throws "Cannot read properties of undefined". Why?
  2. 2.An arrow function written inside a method uses which this?

0 of 2 right so far. Get all two to finish this topic.