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?

Logan Lee
  • 807
  • 9
  • 21
  • 1
    Bound functions cannot be rebound. – kelsny Oct 23 '22 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. – Bergi Oct 23 '22 at 21:40

1 Answers1

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614