Explore apply(), call() and bind() methods in Javascript

When you've researched something on internet related to javascript, you might see apply, call and bind methods. Sometimes you got confusing of them about the purpose and how to use them.

They are useful in many case of situations. For instance, you may need to use bind methods to bind the context(this) into a callback function, we will go for detail later in the post.

I can divide them into two groups:

apply and call

It will CALL the function

function sayHello() {  
    console.log('Hello!');
}

sayHello.call();  
//display 'Hello!' in console

Why don't we call the function directly sayHello(); like this but we use apply and call instead. I'm going to show you the main purpose of them that is BORROW functions.

We have some users object:

let nguyen = {  
    name: 'Nguyen'
}

let john = {  
    name: 'John'
}

These users we retrieve from server via API call. And we there is existing function show name on console,

let base = {  
    name: 'Base',
    showName: function(title) {
        console.log(this.name + '-' + title);
    }
};

Now we're going to show name of nguyen and john:

base.showName.call(base, 'Developer');

base.showName.call(nguyen, 'Engineer');

base.showName.call(john, 'Desginer');

// Base-Developer
// Nguyen-Engineer
// John-Desginer

So now you can see how it BORROW showName function.

What is different from apply and call while they have the same purpose?
With apply, it calls a function with a given this value and arguments provided as an array.
With call, it calls a function with a given this value and arguments provided individually.

base.showName.apply(base, ['Developer']);

base.showName.apply(nguyen, ['Engineer']);

base.showName.apply(john, ['Desginer']);

// Base-Developer
// Nguyen-Engineer
// John-Desginer

bind

It will RETURN the function

bind is useful when you pass a callback function to handle an event with arguments. I got an example for you.

// *This code doesn't work

function showName(name) {  
   alert('My name is ' + name);
}

$('button').click(showName('John'));

The block code above will never work because click event handle accept a function as a callback but we called showName() function.

So we may need bind to solve this problem.

function showName(name) {  
   alert('My name is ' + name);
}

let myName = 'John';

$('button').click(showName.bind(null, myName));

Why null? Because this is a place we will put a context to the function(like apply and call), in this case we don't need any context so we use null.

There is another approach to pass arguments into a callback function you can check it out.

That's all basic concept of apply, call and bind. Understand them help us know javascript much better ;).

Nguyen Tran

I'm Nguyen, a full stack web passion for frontend and love Angular.

Subscribe to Nguyen Tran

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!