Javascript is a lightweight, single-threaded, and cross-platform programming language that enables you to do a lot of things like create dynamically updating content, control multimedia, interactive maps, and animate 2D/3D images.
Javascript provides a few built-in functions for performing various operations. In this post, we will compare the call(), apply() and bind() functions to learn their usage and differences.
The call() method is used to call a function with a specified this value and arguments provided individually.
The apply() method is used to call a function with a specified this value and arguments provided as an array.
The bind() method creates a new function with a specified this value and a specified sequence of arguments preceding any provided when the new function is called.
call() takes the context object as the first argument and passes individual arguments to the function.
function message() {
console.log('Hello, ' + this.msg);
}
const title = { msg: 'GetDifferences' };
message.call(title); // Outputs: Hello, GetDifferences
apply() takes the context object as the first argument similar to call() function and passes arguments as an array to the function.
function message(greeting) {
console.log(greeting + ', ' + this.msg);
}
const title = { msg: 'world' };
message.apply(title, ['Hello']); // Outputs: Hello, world
bind() takes the context object as the first argument and it binds one or more arguments to the new function.
function message(greeting) {
console.log(greeting + ', ' + this.msg);
}
const title = { msg: 'world' };
const messageTitle = message.bind(title);
messageTitle('Hello'); // Outputs: Hello, world
call() executes the function immediately with the specified this value and arguments.
apply() is particularly useful when you have an array-like object and you want to pass its elements as arguments to a function.
bind() does not execute the function immediately instead it returns a new function with specified context and arguments.
Thanks for reading!
If you like the content, please do not forget to subscribe the GetDifferences channel.