A conversation with the 'this' keyword in Javascript
Tags: javascript, codenewbie, developer
Published: 2020-09-18 11:24:25

'This' is one of the most confusing concepts in Javascript. Here's the sad news. It is just as important to understand it as it is hard to understand it. Hahaha. No pun intended. I managed to get a closed interview with 'this' and in here I will share what we talked about.

Karen : Hi 'this'. It is an absolute pleasure to meet you. On behalf of developers all around the world, we have a great need to get to know you better.

this : Hi Karen! That's absolutely fine. I'm suprised that you had the courage to approach me. Time and time again, the other developers have been too scared to talk to me. What would you like to know?

Karen : Thanks for the compliment. I would like to know more about you. Who are you, 'this'?

this : Well, at the very basic. I am a property of any execution context in which I am called. The value I hold depends on the context or situation in which I am used. This value is determined by how the context I am used in is called during runtime.

Karen : Waow. That is amazing. I can almost imagine you as a chameleon. You can change whenever you want to. Can you give us a few examples of how your value might change based on execution context? 

this : Absolutely! Let's get started. You're Karen right? How old are you and what is your profession?

Karen : Hmmn! I'm 17 and I am a full stack developer.

this : Lit! First, I will show you what my execution context is when I am used inside an object method. Permit me to quickly create an object called Karen, like so....

```
const developerKaren = {
  age: 17,
  profession: "Full stack Developer",
  func :function() {
    return this.age;
  },
};

console.log("Karen, it is so nice to know that you are " + 
 developerKaren.func());
```

Now, can you guess what the value of the console.log will be?

Karen : I am not sure! You tell me

this: Okay, in this case, the console.log will output the following.. Karen, it is so nice to know that you are 17.

Karen : Hmmn! That's a little weird. this.age translated to 17? How's that?

this : Well, remember I said that my value depends on the context in which I am called. In this case, since I am being used inside an object method, which is how functions inside objects are called in javascript, I refer to the object whose method is called. In this case, I am being called on the developerKaren object and hence one of my keys, age can be accessed. 

Karen : Hmmn! I think I get you now. 

this : Just so we are sure, what do you think the console.log outputs in this case?
```
var karen = {
 age : 17, 
 profession : "Full Stack Developer"
}

function standAlone(){
return this.age;
}

karen.func = standAlone;
console.log(karen.func());

```

Karen : Mad oh! Now I'm confused! 

this : Hahaha! You need not be. Let's look at it together. In the first block, karen is still an object with two keys, age and profession. Now I created a new function called standAlone that returns this.age.

Karen: Exactly my point. Just what does this refer to here? 

this : That's a good question. It doesn't refer to anything just yet. But what happens when I say, karen.func = standAlone?

Karen : I still don't get it.

this : That's fine. Can you remember what karen is?

Karen : Sure! That's an object with the keys age and profession.

this: Exactly, now by saying karen.func = standAlone, I just created a third key in the karen object and that key holds the function standAlone as its value. Can you now figure out what 'this' will refere to?

Karen : Oh now! I get it. this now refers to the karen object and it now has three keys, age, profession and func. 

this : Exactly! I knew you were brilliant

Karen : Thanks! So, in essence, this is the same as the previous example.

this : You can say so. I brought out this example to prove a point. My value when used in an object method is not affected by where the function is defined. What matters is that the function, or better called method is invoked as a member of an object. That way, I can refer to the object and then I can be used to access all the object's other properties.

Karen : Waow! That was such a beautiful explanation. 

this : Thanks, Karen

Karen : Are there any other contexts in which you can be used?

this : You bet! Let's talk of another context in which my value will be different. When I am used in the Global context. The global context in simple terms means that I am invoked outside of any function. In this case, I refer to the global object. 

Karen : What is the global object?

this : I knew you'd ask. The global object simply refers to the window object , especially in web browsers. Take a look at this example,
```
console.log(this === window); 

a = 37;
console.log("The value of this in the global context is " + this.a); 

this.b = "MDN";
console.log(this.b)  
console.log(window.b)   
```
What do you think the value of the first console.log will be?

Karen : That would be true

this : that's right. since this in the global context is equal to window object then they would be equal. How about the second console.log()?

Karen : The value of this in the global context is 37?

this : That's right. How did you reach that conclusion?

Karen : Well, since a is not declared inside any function or class, its just sitting on the window object, hence this.a will be the value of a on the window object which will be 37

this : That's absolutely correct. The same applies for the last two console logs(). their values will be MDN since window. b = "MDN" and this.b ="MDN" is simply assigning the value MDN to a the window object as a member. Have you been enjoying our discussion so far?

Karen : Absolutely! Let's move on

this : Sure, the next context to talk about is the function context. When used in a function, the value I hold will depend on how the function is called. Here is an example:
```
function f1() {
  return this;
}

f1();
```
What do you think 'this' refers to in this case?


Karen : This is a little confusing. I'm thinking the window object? But I am not sure.

this : That's fine. You are right. But we need to be sure. Why would I refer to the window object in this case? Look carefully and see if you can figure out the reason.

Karen: Hmmn! I think it refers to the window object since at the point of its call, it is not been explictly bound to an object or anything of that sort.

this : Exactly! You saw above that while the place where the function is defined doesn't really matter, where it is invoked matters because that will determine the value of 'this'. In this case f1() is being invoked, but not as a member of an internal object so it automatically defualts to the global object.

Karen : Okay! That makes a lot of sense.


this : However, while still under this function execution context. I have to introduce you to a friend. He's called 'strict'

Karen : Waow! 

Strict : Hi there, Karen. I see that you've been having a fruitful discussion with my friend 'this'.

Karen : That's true. It's a pleasure to meet you. Can I get to know you?

Strict : Sure, I am strict and I prevent you from writing sloppy code.

Karen : Nice to know!

this : So strict, could you explain how using you can affect what I refer to while in the function context?

Strict: Sure! Karen, take a look at this example

```
function f2() {
  'use strict';
  return this;

f2();
}

```
what do you think this would refer to in this case?

Karen : The window object?

Strict: Nah! Look closer. Do you see this string 'use strict'?

Karen : Yes, I see it.

Strict : If you were writing sloppy code, this would have referred to the window object but not when I am around. Since I am here when f2() is invoked, it will not refer to the global object. Rather, it's value will be undefined. 

Karen: hmmn! That's weird.

Strict : Is it though? Think of it logically. Would you really want a function invocation to refer to the window object? Anyways, even if you did, that would be sloppy code and I would not allow it.

Karen: Hmmn, Strict. You sound like someone who doesn't take nonsense.

Strict : To be fair, I play a lot but I am strict when it comes to allowing people to write sloppy code. We don't do that here.

Karen : hahaha! Noted!

this : Thanks friend. Karen, are you tired yet?

Karen : Not a bit. This is so much fun! Any more gems to share?

this : Sure! Let's talk about what I refer to in the class context. There are some similarities between my value in classes and functions but there are little cavaets. Let's discuss them.
Within a class constructor, 'this' is a regular object. All the non-static methods of the class are added to the prototype of this.

Karen : This time around, I don't get it at all.

this : No worries! I'll explain as best as I can. Understanding what I mean in this context has to be the most difficult. Let's use an example to explain

```
class Example {
  constructor() {
    console.log(this.first);
  }
  first(){
  return("I am a nonstatic member of class Example")
  }
  second(){}
  static third(){}
}

new Example(); 

```
In this example, there are certain things we must understand. First, a constructor is a method that is automatically called every time an object is created out of a class. In this case, within the constructor function, I am logging this to the console. Can you guess what the value will be?

Karen : Not at all

this : Within the class constructor, I am a regular object, ie one that can access all the other non-static members of the class, like the first and second functions. Therefore, in this example, once the new object of class example is created, it automatically runs the construtor in which case, this is returned ...

second(){
  return ("I am another member of this class")
  }

I will drop some helpful resources to help you read more on my usage in the 'class context'

Karen : Okay! That will be helpful

this : There are about 2 or 3 more contexts to talk about. But I am getting tired.

Karen : Awwn! You've been a huge help to me today. I'm sure the other developers will be happy to learn all you've taught me so far. Maybe we could schedule another interview soon?

this : Definitely! It was wonderful speaking to you, Karen.


### SUMMARY
Here are the common contexts in which the 'this' keyword can be used. We have spoken about some of them. Be sure to read up on the others. 
1. Global Context
2. Function Context
3. Class Context
4. Derived Class Context
5. this in arrow functions
6. this in object methods
7. this as a constructor .... and much more.

That was a hypothetical interview between me and the 'this' keyword. I hope in some way, I have simplified your understanding of this difficult concept. I did not want the article to be too long so that full understanding can be derived. If you would like a part two where I dive deep into the other contexts where the 'this' keyword finds usage, kindly let me know. Also, this is the first post in a series, where I aim to help us attain mastery of some of the weirdest Javascript concepts. Yes, myself included. If you would be interested in that series, please drop a comment down below. 

In the meantime, here are some helpful articles to help you solidify your understanding of the 'this' keyword.


[this - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this)
[this - W3Schools](https://www.w3schools.com/js/js_this.asp)
[this - tutorialsTeacher](https://www.tutorialsteacher.com/javascript/this-keyword-in-javascript)

Contact Me:
[Twitter](https://twitter.com/EfereyanK)