DEV Community

loading...

What are call(), apply() and bind() in JavaScript

amitavmishra99 profile image Amitav Mishra Originally published at jscurious.com ・2 min read

In JavaScript this refers to the owner object. If you want to attach some extra properties to a function, then you can do that with these 3 methods and can access that extra property using the this keyword. Let’s learn in deep about these 3 methods.

The call() method

The call() method calls a function with a given value and other arguments provided in the function.

const address = {city: 'Sonepur', state: 'Odisha'};

function print(name) {
    console.log('Name: ' + name + ', Address: ' + this.city + ', ' + this.state);
}

print.call(address, 'Amitav');
// Name: Amitav, Address: Sonepur, Odisha
Enter fullscreen mode Exit fullscreen mode

Here in the example above, call() attaches the address object to the print() function and print() function can access this address object using this.
You can provide any type of value for this.

function print() {
    console.log('Hello ' + this);
}

print.call('World'); // Hello World

print.call(245); // Hello 245
Enter fullscreen mode Exit fullscreen mode
function print() {
    console.log(this[0] + ' ' + this[1]);
}

print.call(['Hello', 'World']); // Hello World
Enter fullscreen mode Exit fullscreen mode

The apply() method

This method invokes the function and allows you to pass the arguments as an array.

const address = {city: 'Sonepur', state: 'Odisha'};

function print(name, age) {
    console.log(name +', Age: ' + age + ', Address: ' + this.city + ', ' + this.state);
}

print.apply(address, ['Amitav', 24]);
//Amitav, Age: 24, Address: Sonepur, Odisha
Enter fullscreen mode Exit fullscreen mode

Both call() and apply() works the same way. The only difference is that call() expects all parameters to be provided one by one, whereas apply() allows you to pass in arguments as an array.

The bind() method

This method returns a new function with the value bound to it, which you can use to call the function with the required arguments.

const address = {city: 'Sonepur', state: 'Odisha'};

function print(name, age) {
    console.log(name +', Age: ' + age + ', Address: ' + this.city + ', ' + this.state);
}

const bindAddress = print.bind(address);

bindAddress('Amitav', 24);
//Amitav, Age: 24, Address: Sonepur, Odisha
Enter fullscreen mode Exit fullscreen mode

You may also like

Thanks for your time
Find more Web dev blogs on jscurious.com

Discussion

pic
Editor guide