0

I have a question about Function.prototype.bind.

function f() {
  return this;
}

const g=f.bind({foo:'foo'});
const h=g.bind({bar:'bar'});

console.log(h());    // expected {bar:'bar'} but get {foo:'foo'}

I was expecting the above snippet to produce either {foo,bar} or {bar} but instead I get {foo}.

Can you explain what is going on?

2
  • 1
    Bound functions cannot be rebound. Commented Oct 23, 2022 at 21:37
  • Calling bind() creates a new function that will ignore its this argument. No matter what you pass to that function, or .bind() it again, it's ignored. Commented Oct 23, 2022 at 21:40

1 Answer 1

1

Using .bind() to create a function that "fixes" the value of this in the called function results in a function where this cannot be overridden.

What you get back from .bind() is a new function that will pass along arguments to the original target function, with a guarantee that in that called function the value of this will be what you ask for. Re-binding that function therefore does no good: you do get back a new function, but it calls a function (the first bound function) that explicitly ignores its own this value.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.