How to bind function arguments without binding this with JavaScript?

Estimated read time 1 min read

In JavaScript, you can bind function arguments without binding this by using the apply or call methods.

Here’s an example using the apply method:

const add = function(a, b) {
  return this + a + b;
};

const sum = add.apply(10, [1, 2]);
console.log(sum); // Output: 13

In this example, the apply method is used to call the add function and set its this value to 10. The arguments 1 and 2 are passed to the function as an array.

Here’s an example using the call method:

const add = function(a, b) {
  return this + a + b;
};

const sum = add.call(10, 1, 2);
console.log(sum); // Output: 13

In this example, the call method is used to call the add function and set its this value to 10. The arguments 1 and 2 are passed to the function as separate arguments.

Both the apply and call methods are used to invoke a function with a specified this value and arguments. The difference between the two is that the apply method takes the arguments as an array, while the call method takes the arguments as separate values.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply