Hello, my name is: Amy

Explain Function.prototype.bind. (Also: What's the difference between `.call` and `.apply`?)

this in JavaScript is equal to the object where a function is called. There are three function methods available to change the value of this if needed. One of these ways is with .bind().

Function.prototype.call and Function.prototype.apply

To put bind in perspective, I'll first go over the first two ways, call and apply. Both of these function methods allow you to pass in the this value a particular function should execute with as their first argument. The difference between call and apply is only in how you define the parameters of the initial function.

function move(direction) {
  console.log(`Move ${this.amount} miles ${direction}.`);
}

var car = {
  amount: 20
}
var bike = {
  amount: 2
}

// with `call`, parameters for move function are passed in each as own argument 
move.call(car, 'north'); // --> "Move 20 miles north."

// with `apply`, parameters for move function are passed in array as one argument
move.apply(car, ['south']); // --> "Move 2 miles south."

Function.prototype.bind

bind is similar in that the first argument to bind is still the this value you wish to execute with. The difference is that the other arguments passed in represent ones that should permanently be passed into that function.

In the example below, I've created a special move function for Santa to go home. Since he will ALWAYs be going North, I have passed the value into the bound function so it will no longer need to be provided as arguments each time Santa moves.

function move(direction, amount) {
  console.log(`Move ${amount} miles ${direction}.`);
}
var sleigh = {
  amount: 15
}

// bind to move function, and say direction should ALWAYs be 'north'
var goHomeSanta = move.bind(sleigh, 'north'); 

goHomeSanta(); // --> "Move 15 miles north."

Fun Fact: You don't even have to pass in an object value for this if you don't need to, null can be passed if you just need to permanently set values of arguments (and it's appropriate to not have a this assignment).

Comments