All 28 lessons ▾
Inside JavaScript · Lesson 27 of 28
The this Keyword Part 1: Global Scope, Functions and Strict Mode
So, this can be window, undefined, or an object, in the very same function. So let's finally understand the most confusing word in JavaScript.
A new lesson goes up every day at 11 am. Subscribe on YouTube so you don't miss it.
Got a doubt? Ask in the comments under the video.Subscribe
- this depends on how a function is called
- Global space: the global object (window)
- Plain call, non-strict: substituted with window
- Plain call, strict mode: undefined
- Called on an object: this is that object
- Modules and classes are always strict
Part 1What decides this?
So we've reached the last big topic of the course. The this keyword. It confuses almost everyone, because it doesn't behave like a normal variable. Now open the MDN page on this right now, and it's full of jargon. But by the end of part two, you'll understand every line of it. So today, I'll give you one rule that explains almost everything. Remember episode five? We saw that every execution context gets its own this. Now we find out what decides its value.
So here's the rule. Remember this. The value of this depends on how a function is called, not where it's written. That's the opposite of scope! Scope is lexical. It follows where the code sits. But this is decided at the moment of the call, by the way you call it. Same function, called differently, gets a different this. So keep this rule in mind, and everything today will make sense.
1function describe() {2 return this.title + " is " + this.mins + " minutes";3}4 5const a = { title: "Inception", mins: 148, describe };6const b = { title: "Interstellar", mins: 169, describe };7 8a.describe(); // Inception is 148 minutes9b.describe(); // Interstellar is 169 minutesBut why does JavaScript even have this? To reuse one function for many objects. So here's a single function, describe, that reads this.title, and this.mins. We put the very same function inside two movie objects, a and b. When we call a.describe, this is a, so we get Inception is one forty eight minutes. When we call b.describe, this is b, so we get Interstellar. One function, written once, and this tells it which object to work on, at the moment of the call. So that's the whole point of this.
Now here's a picture to make it stick. Think of this like the word I. When I say I, it means me. When you say I, it means you. Same word, but who it points to depends on who's speaking. So this works exactly the same way. Same function, but the object it points to depends on who calls it. Keep that in mind, and this will never feel random again.
So here's our road map, for two episodes. Today, part one. This in the global space. This inside a function. Strict mode, and something called this substitution. Next time, part two. Object methods. call, apply, and bind. Arrow functions. And this in the DOM. So grab a notebook, and let's go case by case.
Part 2this in the global space
So let's start at the very top of the program. The global space.
1console.log(this);2// in a browser: Window {...}3 4console.log(this === globalThis);5// trueSo at the top level of a script, outside any function, this is the global object. In a browser, that's window. We saw it in episode five. This equals window, at the global level. And remember globalThis? It's the name for the global object that works everywhere. So at the top level, this equals globalThis, and the second line prints true. But now the global object depends on where JavaScript runs. In browsers, it's window. In Node.js, it's called global, though at the top of a Node file, this is actually module.exports, an empty object. Different runtime, different answer. In the browser, though, the global space is the simple case. This is window, every time.
Part 3this inside a function
Now the interesting part. What is this inside a normal function? The answer depends on something called strict mode. So let's see both, line by line.
1function show() {2 console.log(this);3}4 5show();6window.show();Window {...}
Window {...}So first, normal mode, which people often call non-strict mode. Phase one stores show, and the global memory already has this, as window. Line five calls show, plain, with nothing in front of it. Inside, this starts as undefined, because show wasn't called on any object. But in non-strict mode, JavaScript doesn't like an undefined this. So it quietly replaces it with the global object. This becomes window. Line two logs it, and prints the window object. Then show is done. Line six calls window.show. This time, show is called on window, so this is window directly. So same output, but for a different reason.
Now that replacement has a name. This substitution. Remember this. If the value of this would be undefined or null, non-strict mode substitutes the global object instead. So that's the only reason this is window inside a plain function call. The function never asked for window. JavaScript just filled the gap.
1"use strict";2 3function show() {4 console.log(this);5}6 7show();8window.show();undefined
Window {...}So now let's turn on strict mode, by writing use strict at the very top. Same function. Line seven calls show, plain. Inside, this is undefined, and this time, there's no substitution. Strict mode leaves it as it is. Line four prints undefined, and show is finished. Line eight calls window.show. show is called on window, so this is window. And it prints the window object. So in strict mode, how you call the function really decides everything.
So remember this. In strict mode, a plain function call gives this as undefined. No substitution. And when you call it on an object, like window.show, this is that object. Same function, two calls, two values of this. So that's our rule in action. How you call it decides this.
1const movie = {2 title: "Inception",3 show: function () {4 function inner() {5 console.log(this); // not movie!6 }7 inner();8 },9};10 11movie.show();And now here's the trap that catches almost everyone. show is called as movie.show, so inside show, this is movie. Now, inside show, we write another function, inner, and call it. What's this inside inner? Most people say movie, because inner is written inside show. But no! Now look at how inner is called. inner, with nothing before it. A plain call! So its this is undefined in strict mode, or window without it. Never movie. Where a function is written doesn't matter for this. Only the call does. So we'll fix this neatly with an arrow function, in the next episode.
Part 4What is strict mode?
Now since strict mode changes this, let's quickly understand what strict mode actually is.
1"use strict";2 3score = 10;4// ReferenceError: score is not defined5 6function f() {7 return this;8}9f(); // undefinedSo strict mode is an opt-in, safer version of JavaScript. You turn it on with the string use strict, at the top of a file, or at the top of a function. It turns silent mistakes into real errors. For example, without strict mode, assigning to a variable you never declared, like score equals ten, quietly creates a global variable. A classic bug! Now in strict mode, it throws a reference error instead. And as we saw, this inside a plain call stays undefined.
And now here's something important for modern code. JavaScript modules, the files that use import and export, are always in strict mode, automatically. So are classes. You don't even need to write use strict. So that means in most modern projects, a plain function call gives this as undefined. So don't be surprised when you see it.
1"use strict";2 3function who() {4 return this;5}6 7console.log(who());8console.log(window.who());9console.log(this === window);Three lines, all in strict mode. What does each one print?
Show the answer
The first calls who plainly, so it's undefined. The second calls it on window, so it's window. And the third is at the top level, where this is still the global object, even in strict mode. So, true. Undefined, window, true. Did you get all three?
In the comments, explain in your own words why this is window inside a plain function call, without strict mode. Use the words, this substitution.
Show the answer
In a plain call like who(), there's nothing before the dot, so JavaScript sets this to undefined.
Without strict mode, a rule called this substitution kicks in: when this is undefined or null, it's replaced with the global object. In the browser, the global object is window, so this becomes window.
In strict mode there's no this substitution, so this stays undefined.
Try it first, then post yours in the comments under the video.
The video on YouTube, and the lesson as a swipe-through on Instagram.