como-funciona-call-apply-bind-en-javascript

How Call, Apply, and Bind Work in JavaScript

  • 5 min

When working with JavaScript, it’s common to encounter situations where we need to control the value of this.

This is where the call(), apply(), and bind() methods come into play. These methods allow us to explicitly set the context of this for a function.

MethodDescriptionExecution
callExecute a function immediately with a specific context.Immediate
applySimilar to call, but when arguments are in an array.Immediate
bindTo create a new function with a fixed context.Not immediate

These methods are very useful when we want to ensure that this points to the correct object, regardless of how the function is invoked (so it doesn’t get “lost”).

The call() Method

The call() method allows calling a function with a specific value for this and passing arguments one by one.

The syntax for call() is as follows:

functionName.call(thisArg, arg1, arg2, ...);
Copied!
  • thisArg: The object you want to associate with this when the function executes. This defines the context.
  • arg1, arg2, …: The arguments passed to the function, listed one by one.

Let’s see it with an example:

function greet(greeting) {  
  console.log(`${greeting}, I am ${this.name}`);  
}  

const person = { name: "Luis" };  

greet.call(person, "Hello");  // Output: "Hello, I am Luis"  
Copied!
  • The saludar function does not have its own this object.
  • We use call() to set the value of this to the persona object.
  • We pass the argument "Hola" directly as a parameter.

The apply() Method

The apply() method works similarly to call(), but the arguments are passed as an array or list.

The syntax for apply() is:

functionName.apply(thisArg, [arg1, arg2, ...]);
Copied!
  • thisArg: Same as in call(), it’s the value to be assigned to this.
  • [arg1, arg2, …]: An array or iterable object containing the arguments for the function.

If we look at an example, it could be:

function introduce(name, age) {  
  console.log(`My name is ${name} and I am ${age} years old. I am ${this.profession}`);  
}  

const context = { profession: "developer" };  

introduce.apply(context, ["Luis", 30]);  
// Output: "My name is Luis and I am 30 years old. I am developer"  
Copied!

apply() is useful when you have arguments stored in an array or need to pass them dynamically.

The bind() Method

Unlike call() and apply(), the bind() method does not execute the function immediately.

Instead, it returns a new function with the value of this bound to the specified context.

The basic syntax of the .bind() method is as follows:

functionName.bind(thisArg[, arg1[, arg2[, ...]]]);
Copied!
  • thisArg: The value to be associated with this when the function executes. This defines the function’s context.
  • arg1, arg2, ... (optional): Arguments that are passed before the arguments the original function would take.
const person = {  
  name: "Luis",  
  greet: function() {  
    console.log(`Hello, I am ${this.name}`);  
  }  
};  

const greeting = person.greet.bind(person);  
greeting();  // Output: "Hello, I am Luis"  
Copied!

Let’s see it with an example. bind() is useful for ensuring that this remains fixed, even when the function is used in other contexts.

const object = {
    name: "Luis",
    greet: function() {
        console.log(`Hello, my name is ${this.name}`);
    }
};

const greetLuis = object.greet.bind(object);
greetLuis(); // "Hello, my name is Luis"
Copied!

In this example,

  • By using bind, we create a new function saludarLuis that will always have this pointing to the objeto object.
  • This guarantees that, when invoked, the saludar method correctly accesses the nombre property.

Practical Examples

These examples show how Call, Apply, and Bind work. It does not mean they are always the best way to solve all problems; in some cases, there may be more suitable solutions.