November 23, 2018
“Hey JS… What is this?”
If the function returns something, the computer returns its value back to the point where the function was called.
Here’s where the keyword this comes in… And where things start to get interesting. this is a reference to the calling context of a function. Whenever we access this inside a function, we actually access the function’s specific execution context. So we needn’t take a look at the function itself, but at how the function was called. The problem is that there are different ways of how a function can be called, and all of them provide a different context for this. Seems complicated? It is a bit troublesome, as there are actually five different ways of invoking a function. When we actually know where to look at, things get more straightforward, so let’s take a closer look at these five use cases.
First, let’s build a function that returns this (or its context), Then, let’s call this function.
A special function that just returns its context.
Then, let’s call this function. Here’s the first, and the “normal” use case: By default, this points to undefined.
Side note: In non-strict mode, this points to the “global object”. In the browser, the “global object” is window. This is somewhat unexpected behaviour, so let’s stick to strict mode for now.
Second Case: If the function is invoked as an object property, this points to its object.
Third Case: If the function is invoked via the methods .call() or .apply(), the explicit context (the one that is passed over as an argument) is used.
4th Case: The method .bind() creates a new function with a bound context (it sticks to the one that is passed over as an argument)**.
5th Case: The keyword new always creates a new object with its own context.
The five invocation types and their specific rules for this
See you next week! Thank you for your cool lessons, Johannes Ewald. :)
Judith started an apprenticeship at Peerigon in 2018 to become a professional web developer. As part of her weekly routine, she publishes a blog post each week about what she has been doing and what she has learned.
Learning to code
Irena Reitz, Celestine Auburger, Leonhard Melzer, 05/18/2021
Tanner Hoisington, 04/20/2021
Moritz Jacobs, 02/12/2021
Wir sind Peerigon, eine Agentur für Softwareentwicklung.
+49 821 907 80 86 0