JavaScript
/Intermediate
call(), apply(), bind()
Definition
Three methods available on all JavaScript functions that allow you to explicitly dictate what the `this` keyword refers to when the function executes.
Explain Like I'm New
`call` is like calling an Uber and instantly telling the driver (the function) to go to a specific address (`this`). `apply` is the exact same, but you hand the driver an array of directions. `bind` doesn't call the Uber; it gives you a coupon for an Uber permanently locked to a specific address to use later.
Real World Example
Borrowing a method: using `Array.prototype.slice.call(nodeList)` to convert a DOM NodeList into a real JavaScript array.
Common Use Cases
- •Borrowing methods from other objects
- •Hard-binding `this` in class methods (React class components)
Interactive Example
Loading Code Playground...
Interview Questions
basic
- What is the difference between `call` and `apply`?
intermediate
- What does `bind` return?
advanced
- Can you re-bind a function that has already been bound using `bind()`?