Home > Mobile >  Javascript bind() function
Javascript bind() function

Time:08-27

I need to write a function that accepts and function and an argument and returns the bound version of the the passed in function. Why doesn't my code work?

function bindToAnArg(func, arg){
 

     let myFunc = func.bind(arg);


return myFunc;

}

////Test

function add(num1, num2) {
  return num1   num2;
}

const addTwo = bindToAnArg(add, 2);

console.log(addTwo);

const twoPlusSix = addTwo(6);```

CodePudding user response:

The first argument of bind is what the value of this will be when the function is called. You probably should just pass null. This could would work:

function bindToAnArg(func, arg) {
    return func.bind(null, arg);
}

CodePudding user response:

The first argument to func.bind(...) must be the context (this) of the function. It's probably easier to avoid Function.prototype.bind altogether.

const bind = (f, ...a) => (...b) =>
  f(...a, ...b)

const add = (a, b) =>
  a   b

const addTwo =
  bind(add, 2)

console.log("2 plus 6 equals", addTwo(6))
// 2 plus 6 equals 8

const addMany = (...all) =>
  all.reduce(add, 0)

const addSome = bind(addMany, 1, 2, 3)

console.log("1 plus 2 plus 3 plus 4 plus 5 equals", addSome(4, 5))
// 1 plus 2 plus 3 plus 4 plus 5 equals 15
 

  • Related