In JavaScript, call, apply, and bind are methods that allow you to call a function with a specific value for this and pass in arguments as an array or a comma-separated list. These methods are useful when you want to reuse a function in different contexts or pass a function as a callback.
Here are some examples of how to use call, apply, and bind in JavaScript:
-
Using
call:const greet = function (greeting) { console.log(`${greeting}, my name is ${this.name}`); }; const john = { name: 'John' }; const jane = { name: 'Jane' }; greet.call(john, 'Hello'); // Hello, my name is John greet.call(jane, 'Hi'); // Hi, my name is JaneIn this example, the
greetfunction is called with a specific value forthisusing thecallmethod. The first argument tocallis the value forthis, and the subsequent arguments are passed as arguments to the function. -
Using
apply:const add = function (a, b) { return a + b; }; console.log(add.apply(null, [2, 3])); // 5In this example, the
applymethod is used to call theaddfunction with a specific value forthis(in this case,null) and an array of arguments. -
Using
bind:const logName = function () { console.log(`My name is ${this.name}`); }; const john = { name: 'John' }; const jane = { name: 'Jane' }; const logJohnName = logName.bind(john); const logJaneName = logName.bind(jane); logJohnName(); // My name is John logJaneName(); // My name is JaneIn this example, the
bindmethod is used to create new functions that are bound to a specific value forthis. Thebindmethod returns a new function with the specifiedthisvalue and the same body as the original function. The new function can be invoked like any other function, and its value forthiswill always be the value passed tobind.