Call, apply and bind~ Popular concepts ~

Call, apply and bind

When we know what scope is, it's time to explore the call, apply, and bind methods. They are all touching on the topic of context in JavaScript because they define the this of the passed functions. Consider the following example:

const user = { firstName: "Krasimir" };

function message(greeting) {
  console.log(`${greeting} ${this.firstName}!`);
}
message('Hey'); // Hey undefined!

We want the message function to have user as a context. This so we can use this.firstName. All the three functions above can solve that problem.

const user = { firstName: "Krasimir" };

function message(greeting) {
  console.log(`${greeting} ${this.firstName}!`);
}
message.call(user, 'Hey'); // Hey Krasimir!
message.apply(user, ['Hi']); // Hi Krasimir!
message.bind(user, 'Hola')(); // Hola Krasimir!

call accepts the desired this as a first argument followed by other parameters of the function. apply works the same way except that the additional parameters we pass as an array. bind is a bit different because it doesn't execute the function immediately. It does a partial application (something that we will discuss later). The result of bind is another function that we can run with predefined parameters.