5

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?
6
  • you've already retrieved the variable, which is now stored in func. it that not what you want? Commented Mar 5, 2017 at 0:22
  • 2
    The code above is simply an example, the context in which I have the func variable I do not have the original parameters Commented Mar 5, 2017 at 0:24
  • 1
    I don't think you can. Commented Mar 5, 2017 at 0:31
  • 1
    You can see it in the console under [[BoundArgs]], but I don't think this is accessible in code. Commented Mar 5, 2017 at 0:37
  • 1
    Yup, in my context I can see it as [[Scopes]], in the console you can right click and press "copy property path" and it gives the correct path but trying to evaluate it throws an error saying it's undefined... Just out of curiosity, how are you seeing [[BoundArgs]] in the console? I'm trying to do it with my example but I can't see anything Commented Mar 5, 2017 at 0:42

1 Answer 1

3

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]
Sign up to request clarification or add additional context in comments.

1 Comment

I am not the one binding the function, I just need to retrieve the bound arguments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.