Rob
Rob

Reputation: 63

How to get parameters that have been bound by JavaScript's .bind() function

How do I get the parameters that have been bound to a function?

function add(x){
  return x + 1
}

var func = add.bind(null, x)
// how do I get the value of `x` from the `func` variable alone?

Upvotes: 5

Views: 1995

Answers (1)

Gin Quin
Gin Quin

Reputation: 1113

You cannot natively, but you can create your own bind-like function with few efforts:

function bind(fn, boundThis, ...args) {
  const bound = fn.bind(boundThis, ...args)
  bound.__targetFunction__ = fn;
  bound.__boundThis__ = boundThis;
  bound.__boundArgs__ = args
  return bound;
}

You use it like Function.prototype.bind but you additionally get access to the bound values and the original function:

function addOne(x) {
  return x + 1
}
const two = bind(addOne, null, 1)
console.log(two())  // print 2
console.log(two.__boundArgs__)  // print [1]

Upvotes: 3

Related Questions