# The Magic of this, call(), apply(), and bind() in JavaScript

## What `this` means in JavaScript?

'this' keyword refers to the current context which can be different based on the runtime environments like nodejs or browser.

I will be writing this blog by taking the runtime environment as browser.

## `this` inside normal functions?

'this keyword refers to the window object in sloppy mode and undefined in strict mode.

```javascript
function whatIsThisInStrictMode(){
    'use strict';
    console.log(this);
}

function whatIsThisInSloppyMode(){
    console.log(this);
}

whatIsThisInStrictMode();
whatIsThisInSloppyMode();
```

## `this` inside objects?

'this' inside the object refers to that particular object itself.

```javascript
const user = {
    name : 'Kartik',
    whoIsThisInUserObject : function () {
        console.log(this);
    }
}

console.log(user.whoIsThisInUserObject());
```

## Implicit Binding and Explicit Binding

When this keyword is by default referring to the current context itself that is the Implicit binding that JavaScript does automatically.

But we can override that Implicit binding to whatever object we want using call, appy and bind methods.

```javascript
const user = {
    name : 'Kartik',
}

function getName(lastName){
    console.log(this.name);
}

getName(); //Currently this = window object, but we can bind it with user object
```

## What `call()` does?

It helps in binding the new object with this and call the function immediately.

```javascript
const user = {
    name : 'Kartik',
}

function getName(honorific, lastName){
    console.log(honorific + '. ' + this.name + ' ' +lastName);
}

getName.call(user,'Mr', 'Kumar');
```

## What `apply()` does

It also calls the function immediately but takes the argument as an array rather than individual values.

> Trick : a for apply and a for array, apply() takes argument as array.

```javascript
const user = {
    name : 'Kartik',
}

function getName(honorific, lastName){
    console.log(honorific + '. ' + this.name + ' ' +lastName);
}

getName.apply(user,['Mr', 'Kumar']);
```

## What `bind()` does

It works same as call, the only difference is that it returns reference to the binded function rather than calling it immediately.

```javascript
const user = {
    name : 'Kartik',
}

function getName(honorific, lastName){
    console.log(honorific + '. ' + this.name + ' ' +lastName);
}

const bindedGetName = getName.bind(user,'Mr', 'Kumar');

bindedGetName();
```

## Difference between call, apply and bind?

Here’s a **clear comparison chart** for `call()`, `apply()`, and `bind()` in JavaScript.

| Feature | `call()` | `apply()` | `bind()` |
| --- | --- | --- | --- |
| **Execution** | Executes **immediately** | Executes **immediately** | **Does NOT execute immediately** |
| **Arguments format** | Passed **comma separated** | Passed as an **array** | Passed **comma separated** |
