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

## Introduction

In JavaScript, one concept controls how functions behave depending on how they are called. That concept is the `this` keyword. Along with `this`, three powerful methods — `call()`, `apply()`, and `bind()` — allow you to control what `this` should be.

If you understand these properly, you gain full control over function execution in JavaScript.

## What `this` Means in JavaScript

`this` refers to the object that is calling the function.

It is not decided where the function is written. It is decided when the function is called.

***Caller → Function →*** `this`

Whoever calls the function becomes the value of `this`.

## `this` Inside Normal Functions

```js
function show() {
  console.log(this);
}

show();
```

*   In non-strict mode → `this` is the global object
    
*   In strict mode → `this` is `undefined`
    

## `this` Inside Objects

```js
const user = {
  name: "Prakash",
  greet() {
    console.log(this.name);
  }
};

user.greet();
```

Output:

```js
Prakash
```

Here, `user` is calling the function, so `this` refers to `user`.

## Calling Context Changes `this` (Very Important)

```js
function show() {
  console.log(this);
}

const obj = {
  show
};

// Direct call
show();        // global / undefined

// Object call
obj.show();    // obj
```

This proves one rule:

`this` is decided at call time, not at definition time.

## Function Borrowing Problem

Sometimes you want to use a method of one object with another object without copying it.

```js
const user1 = {
  name: "Prakash",
  greet() {
    console.log(this.name);
  }
};

const user2 = {
  name: "Rahul"
};

user1.greet(); // Prakash
```

Now we want `user2` to use `greet`. This is where `call()`, `apply()`, and `bind()` help.

## What `call()` Does

`call()` allows you to set `this` manually and immediately execute the function.

### Syntax

```js
functionName.call(thisArg, arg1, arg2)
```

### Example

```js
user1.greet.call(user2);
```

Output:

```js
Rahul
```

## What `apply()` Does

`apply()` is similar to `call()`, but it takes arguments as an array.

### Syntax

```js
functionName.apply(thisArg, [arg1, arg2])
```

### Example

```js
function introduce(city, country) {
  console.log(`${this.name} lives in ${city}, ${country}`);
}

const user = { name: "Prakash" };

introduce.apply(user, ["Roorkee", "India"]);
```

## What `bind()` Does

`bind()` does not execute the function immediately. It returns a new function with `this` permanently set.

### Syntax

```js
const newFn = functionName.bind(thisArg)
```

### Example

```js
function greet() {
  console.log(this.name);
}

const user = { name: "Prakash" };

const boundFn = greet.bind(user);
boundFn();
```

## Real-World Use of `bind()`

```js
const user = {
  name: "Prakash",
  greet() {
    console.log(this.name);
  }
};

setTimeout(user.greet.bind(user), 1000);
```

Without `bind()`, `this` would be lost.

## Arrow Functions and `this` (Important)

```js
const user = {
  name: "Prakash",
  greet: () => {
    console.log(this.name);
  }
};

user.greet(); // undefined
```

Explanation:

*   Arrow functions do not have their own `this`
    
*   They take `this` from their surrounding scope
    

## Visual Understanding

![Image](https://images.openai.com/static-rsc-4/yHKtjOUlQVGJIC94qJruuiOWz69qIcZF9dGByLQ0vTtVHNlOGCj-8WmH3kmeF7JdbhrO5uZKG5qxdNFgL63AvGqpqcDLMbVFakwMOnGeFAeq5hy0qthfzksTDQQFaxQHfoKs3jS_GGQV2j13lfue07NdTBhs40D0rsWNBjXiTwBrlaAzklWNVkrfF2U5IdWl?purpose=fullsize align="center")

![Image](https://images.openai.com/static-rsc-4/0pu3317ObduCCn2vCGdKzQ0WvQOYDCHvNNq07Jr-Gz1DWMYlfsrGI_CxKU-fu77OMh-gYvMPY87ukR0dho475UG6PAlImCYdiu5p56UdPn58GjBFQIRDSvPAIfeIdC5JRRyj8SliW3ncHps7QEZBe4wUeowvvuS_unqKq3jvSfHGw44KETWCnICAf61rJjeP?purpose=fullsize align="center")

*   `call()` → sets `this` and runs immediately
    
*   `apply()` → sets `this`, runs immediately, takes array
    
*   `bind()` → returns a new function
    

## Difference Between `call`, `apply`, and `bind`

| Feature | call() | apply() | bind() |
| --- | --- | --- | --- |
| Executes immediately | Yes | Yes | No |
| Arguments format | Comma-separated | Array | Comma-separated |
| Returns function | No | No | Yes |
| Use case | Quick invocation | Array-based arguments | Reusable function |

## Combined Example

```js
const person1 = { name: "Prakash" };
const person2 = { name: "Aman" };

function greet(age) {
  console.log(`${this.name} is ${age} years old`);
}

// call
greet.call(person1, 21);

// apply
greet.apply(person2, [22]);

// bind
const fn = greet.bind(person1);
fn(25);
```

## Practice Example :

```js
const car = {
  brand: "Tesla",
  show() {
    console.log(this.brand);
  }
};

const bike = {
  brand: "Yamaha"
};

// call
car.show.call(bike);

// apply
function info(speed, type) {
  console.log(`${this.brand} runs at ${speed} and is ${type}`);
}

info.apply(bike, ["120km/h", "sports"]);

// bind
const boundInfo = info.bind(car);
boundInfo("200km/h", "electric");
```

## Common Mistakes

### Losing `this`

```js
const user = {
  name: "Prakash",
  greet() {
    console.log(this.name);
  }
};

const fn = user.greet;
fn(); // undefined
```

### Fix

```js
const fixed = user.greet.bind(user);
fixed();
```

## Quick Summary of Rules

*   Normal function → depends on how it is called
    
*   Object method → `this` is the object
    
*   call/apply → manually set `this`
    
*   bind → returns a function with fixed `this`
    
*   Arrow function → no own `this`
    

## Conclusion

The `this` keyword becomes simple when you focus on one rule:

`this` depends on the caller

The methods `call()`, `apply()`, and `bind()` give you full control over that behavior.

If you master these concepts, you will write cleaner code, reuse functions efficiently, and avoid common bugs in JavaScript applications.

* * *

### **❊ Want More…?**

I write articles on [**blog.prakashtsx.com**](http://blog.prakashtsx.com) and also post development-related content on the following platforms:

*   [**Twitter/X**](https://x.com/prakashtsx)
    
*   [**LinkedIn**](https://www.linkedin.com/in/prakashtsx)
