DEV Community

Discussion on: Understanding Bind, Call and Apply in JavaScript

Collapse
 
pentacular profile image
pentacular • Edited

I think it's worth pointing out that you can bind any or all of the arguments, not just 'this'.

e.g.

const context = {};
function setName(name) {
  this.name = name;
}
const setContextNameToFred = setName.bind(context, 'fred');
setContextNameToFred();
console.log(context);
// { name: "fred" }
Enter fullscreen mode Exit fullscreen mode

And that it also works where 'this' doesn't.

const add = (a, b) => a + b;
const addOne = add.bind(null, 1);
console.log(addOne(2));
// 3
Enter fullscreen mode Exit fullscreen mode

Likewise for apply and call.