JavaScript·100 questions

What are call, apply, and bind?

Answer

The methods call, apply, and bind in JavaScript are designed for explicit control of the execution context of a function, meaning the binding of a specific this value. These are powerful tools that allow you to reuse code and precisely control the execution environment.

Here are the main ways they are used:

The call method invokes a function immediately, allowing you to pass the context as the first argument, followed by the rest of the function arguments separated by commas, for example, fn.call(obj, a, b).
The apply method works similarly by calling the function immediately, but arguments are passed as an array, which is convenient when their number is not known in advance or they are already collected into a collection, for example, fn.apply(obj, [a, b]).
The bind method does not call the function immediately, but instead returns a new function with a hard-bound context and passed arguments, which can be executed later.

The bind method is especially useful when passing methods as callbacks into asynchronous code or event handlers, where the context is often lost. Another important application of these methods is borrowing methods from other objects, such as using array methods to work with array-like objects like arguments or NodeList. Understanding the differences between call, apply, and bind allows you to write more flexible, modular, and predictable code.

Was this answer helpful?

More questions in this topic

Related questions from other topics