“THIS” in Javascript.
Tags: javascript, beginners, programming, webdev
Published: 2022-12-04 12:17:06

**Prerequisites:**
1. Function declaration, expression, and arrow function
2. Objects

---

**What exactly is “this” keyword?**
The execution context contains three components: variable environment, scope chain and this.

`this` is a special variable, that takes the value of the owner of the function, and is created for every function [execution context].  
The value of the keyword is only assigned only when the function is called, and also the value depends on how the function is called and is not static.

If we simply `console.log(this)`. It will return the global object.

`this` keyword doesn't NOT point to the function itself, or the variable environment.


We will look at the ways functions are called and the value the keyword takes:

###1. Method call:

If a function is called through this method, the `this` keyword will point to the object in which it is called for example:

```javascript
//code 
const student={
    name:"Piyush",
    logThis:function(){
        console.log(this)
    }
}


console.log(student.logThis())


// Output: this point to the object where it is called


name: 'Piyush', print: ƒ}
```


###2. Simple function call
    
There are two different values this might point to, it depends on whether the strict mode is enabled or not. 
    
####a. If strict mode is enabled:

It returns undefined.

```javascript
//code 
`use strict`
function print12() {
    console.log(this)
}
console.log(print12())

// output
undefined

```
####b. Without strict mode

It returns the global object.

```javascript
//code 

function print12() {
    console.log(this)
}

console.log(print12())


// output: window object
Window {window: Window, self: Window, document: document, name: '', location: Location, …}
```

###3. Arrow function :
Arrow functions do not get their own “this” keyword. Using this keyword inside the arrow function will simply point to the surrounding function. It is also called the “lexical this” keyword.


```javascript
//code
const student={
    name:"Piyush",
    age:20,
    print12:()=> {
        console.log(this)
    }
}
console.log(student.print12())


//output: window object
Window {window: Window, self: Window, document: document, name: '', location: Location, …}

```


Here, “this” does not point to this object where the function is called, but points to the surrounding function, here the global (object).


###5. Method borrowing and this keyword : 
Say we have two objects student1 and student2. Student1 has “printage” method and we copy it to student2.


```javascript
//code
const student1={
    name:"Piyush",
    age:20,
    printage:function() {
        console.log(this)
        console.log("Your birth year", 2022-this.age)
    }
}


const student2={
    name:"ABC",
    age:18,
}


//copying student1.printage method to student2
student2.printage=student1.printage
console.log(student2.printage())


//output
{name: 'ABC', age: 18, printage: ƒ}
Your birth year 2004
```

When this line is executed “printage” method even though it is in student1, “this” points to the object that is calling the method, here student2 is invoking the method so we get the above output.

###6.  Call, apply and bind method:

We can explicitly set up the value of “this” using these methods.


a. Call
     
The first argument in the call method should always be the object we want the “this” keyword to point to.
Here we have two students: student1 and student2.  

We copy “printage” method from student1 and store it in birthyear. birthyear is a regular function.

After that we use `birthyear.call` method, the first argument `student2` is the object we want `this` to reference. After that, we can pass the required arguments for the function.
    
Example :

```javascript
const student1={
    name:"Piyush",
    age:40,
    printage(score) {
        console.log(this)
        console.log("Hi "+this.name+". You scored "+score)
    }
}


const student2={
    name:"ABC",
    age:18,
}


// copy print age
const birthyear=student1.printage


// call method
birthyear.call(student2,20)


//output
{name: 'ABC', age: 18}
Hi ABC. You scored 20
```



So we get, the output: `{Hi ABC. You scored 20}`


b. Apply:

The apply method is similar to the call method. The only difference here is that while calling the apply method the arguments of the function are passed in an array.
Example:

```javascript
//code
const student1={
    name:"Piyush",
    age:30,
    printage(score) {
        console.log(this)
        console.log("Hi "+this.name+". You scored "+score)
    }
}


const student2={
    name:"ABC",
    age:18,
}


// copy print age
const birthyear=student1.printage


// apply method
birthyear.apply(student2,[20])


//output
{name: 'ABC', age: 18}
Hi ABC. You scored 20


```

c. bind :

The bind method is a bit different from the call and apply method. It takes in one argument, i.e the object for `this`, and returns a new function. Now we can use the function to pass arguments.
Example :

```javascript
//code
const student1={
    name:"Piyush",
    age:20,
    printage(score) {
        console.log(this)
        console.log("Hi "+this.name+". You scored "+score)
    }
}


const student2={
    name:"ABC",
    age:18,
}

// the bind method will return a function, while this will point to student2
const birthyear=student1.printage.bind(student2)


//use the function to pass arguments
birthyear(39)


//output
{name: 'ABC', age: 18}
Hi ABC. You scored 39
```