DEV Community

Cover image for call, apply, bind
_Khojiakbar_
_Khojiakbar_

Posted on

13 2 1

call, apply, bind

call

Why do we use call?
We use call when we want to borrow a function from one object and use it with another object.

What is call?
call is a way to use a function with a different object, pretending that object owns the function.

How does call work?
You take a function from one object and call it with another object, telling the function, "Hey, use this other object as your this."

Example:
Imagine you have two friends, Alice and Bob. Alice knows how to introduce herself, but Bob doesn't. You can help Bob introduce himself using Alice's way.

const alice = {
  name: 'Alice',
  introduce: function(greeting) {
    console.log(`${greeting}, my name is ${this.name}`);
  }
};

const bob = { name: 'Bob' };

alice.introduce.call(bob, 'Hello'); // Output: Hello, my name is Bob
Enter fullscreen mode Exit fullscreen mode

apply

Why do we use apply?
We use apply for the same reason as call, but when we want to pass arguments as an array.

What is apply?
apply is similar to call, but it takes arguments in an array instead of individually.

How does apply work?
You take a function from one object and call it with another object, giving the arguments as an array.

Example:
Imagine you want to introduce Bob, but this time you want to say both "Hello" and "Nice to meet you" at once.

const alice = {
    name: 'Alice',
    introduce: function(greetings) {
        const fullGreeting = [...greetings]
        console.log(`${fullGreeting[0]}. My name is ${this.name}. 
        ${fullGreeting[1]}`);
    }
  };

alice.introduce.apply(bob, ['Hello', 'Nice to meet you']); // Output: Hello, my name is Bob
Enter fullscreen mode Exit fullscreen mode

bind

Why do we use bind?
We use bind when we want to create a new function that always uses a specific object as this.

What is bind?
bind creates a new function that remembers which object should be this when it's called.

How does bind work?
You create a new version of a function that always uses the same this value.

Example:
Imagine you want to help Bob introduce himself later, but you want to make sure he does it the right way every time.

const bobIntroduce = alice.introduce.bind(bob);

bobIntroduce('Hi'); // Output: Hi, my name is Bob
bobIntroduce('Hey there'); // Output: Hey there, my name is Bob
Enter fullscreen mode Exit fullscreen mode

Summary with a Simple Story
Imagine you have a magical talking toy named Toy that can say things. Toy belongs to Alice, and it can say her name. You have another toy that belongs to Bob, but it doesn't know how to talk.

call: You tell Toy, "Say Bob's name using your voice," and it says, "Hello, my name is Bob."
apply: You tell Toy, "Say Bob's name and also 'Nice to meet you' using your voice," and it says, "Hello, my name is Bob. Nice to meet you."
bind: You create a new version of Toy that always knows it's talking about Bob. Whenever you tell this new toy to talk, it says, "Hi, my name is Bob."
These magical talking toys are just like functions in JavaScript, and call, apply, and bind help you control which toy is talking!

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (7)

Collapse
 
himanshu_code profile image
Himanshu Sorathiya β€’

Great Explanation, I had difficulties remembering it but you cleared all, thanks

Collapse
 
f1nn0s profile image
Finn Mohr β€’

Hello Khojiakbar,
I am ja beginner in JavaScript. Thank you for your explanation about call, apply and bind.
I have one question about apply. You say : "Imagine you want to introduce Bob, but this time you want to say both "Hello" and "Nice to meet you" at once." , but the output is only : "Hello, my name is Bob." I I expected "Hello, Nice to meet you, Bob". Because you say "at once".
Can you explain me that please ?

Collapse
 
__khojiakbar__ profile image
_Khojiakbar_ β€’

Hello Finn Mohr
Thank you for reading my documentation. I am also learning JS by writing docs for memorising better. To reach the result you commented on, we have to add few lines of code. Sorry, I forgot to provide these lines.

const alice = {
    name: 'Alice',
    introduce: function(greetings) {
        **const fullGreeting = [...greetings]**
        console.log(`${fullGreeting[0]}. My name is ${this.name}. ${fullGreeting[1]}`);
    }
  };

  const bob = { name: 'Bob' };

//   alice.introduce.call(bob, 'Hello'); // Output: Hello, my name is Bob
alice.introduce.apply(bob, **[['Hi', 'Nice to meet you']]**)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
crisarji profile image
crisarji β€’

Great article!, easy to eat and swallow!..

The cover image is perfect and summarizes all!, in the same way the cover has colors, maybe adding colors in the code would be beneficial to remember as well.

Tip: when trying to remember Apply and Call:

  • A..pply has an A..rray

  • C..all is C..omma separated

It worked for me!..

Collapse
 
oculus42 profile image
Samuel Rouse β€’

I like the way you've used an example/story to explain or understand the different methods!

As a warning, please be cautious when using images from other sources as there may be copyright issues.

Collapse
 
nonfungiblehayor profile image
EIbrahim Ayodeji β€’

Great explanation

Collapse
 
emanuelgustafzon profile image
Emanuel Gustafzon β€’

Funny examples that makes it enjoyable to read! Thanks!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay