DEV Community

Hiral
Hiral

Posted on

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

JavaScript beginners often get confused about this. But the idea can be simplified.
Think of this as โ€œwho is calling the function.โ€

  1. this Inside Normal Functions

In a regular function, this depends on how the function is called.

function showName() {
  console.log(this);
}
showName();
Enter fullscreen mode Exit fullscreen mode

In browsers, this usually prints the global object (window).

Because the function was called without an object.

So the caller is the global environment.

  1. this Inside Objects

When a function is inside an object, this refers to the object calling the method.

const person = {
  name: "Alice",
  greet: function () {
    console.log("Hello, my name is " + this.name);
  }
};
person.greet();
Enter fullscreen mode Exit fullscreen mode

Because person is calling greet(), so this becomes person.

What call() Does

call() lets you manually choose what this should be.

function greet() {
  console.log("Hello " + this.name);
}

const person = { name: "Alice" };

greet.call(person);
Enter fullscreen mode Exit fullscreen mode

Even though greet is not inside the object, we force this to be person.

Passing Arguments with call()

function introduce(age, city) {
  console.log(this.name + " is " + age + " years old from " + city);
}

const user = { name: "Bob" };


introduce.call(user, 25, "London");
Enter fullscreen mode Exit fullscreen mode

4. What apply() Does
apply() is almost the same as call().

The only difference:
Arguments are passed as an array

function introduce(age, city) {
  console.log(this.name + " is " + age + " years old from " + city);
}

const user = { name: "Charlie" };

introduce.apply(user, [30, "New York"]);
Enter fullscreen mode Exit fullscreen mode

*What bind() Does
*

bind() does not call the function immediately.

Instead, it creates a new function with this fixed.

function greet() {
  console.log("Hello " + this.name);
}

const user = { name: "David" };

const greetUser = greet.bind(user);

greetUser();
Enter fullscreen mode Exit fullscreen mode

Output

Hello David
Enter fullscreen mode Exit fullscreen mode

Here, bind() creates a new function that always uses user as this.

Top comments (0)