Use of call, apply, and bind in JavaScript
In JavaScript, call
, apply
, and bind
are methods used to manipulate the this
value inside a function.
call
: Thecall
method is used to invoke a function with a specifiedthis
value and individual arguments passed directly.javascriptCopy codefunction greet(name) { console.log(`Hello, ${name}! I'm ${this.title}`); } const context = { title: 'ChatGPT' }; greet.call(context, 'User');
apply
: Theapply
method is similar tocall
, but it accepts arguments as an array.javascriptCopy codefunction greet(name) { console.log(`Hello, ${name}! I'm ${this.title}`); } const context = { title: 'ChatGPT' }; greet.apply(context, ['User']);
bind
: Thebind
method creates a new function with the same body as the original function but with a fixedthis
value. It doesn't immediately invoke the function but returns a new function that can be called later.javascriptCopy codefunction greet(name) { console.log(`Hello, ${name}! I'm ${this.title}`); } const context = { title: 'ChatGPT' }; const boundGreet = greet.bind(context); boundGreet('User');
In each of these methods, the first argument is the this
value to be used in the function. For call
and apply
, subsequent arguments (or an array of arguments in the case of apply
) are the arguments passed to the function. For bind
, it only sets the this
value, and you need to call the returned function separately.
Subscribe to my newsletter
Read articles from Ramdas Hedgapure directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by