PatS
PatS

Reputation: 11524

What does prototype methods don't bind on extraction mean?

When reading why ES6 class methods don't automatically bind "this" to the method, I see answers that say "prototype methods don't bind on extraction", but that means nothing to me. What does "bind on extraction" mean?

When a function is called

obj.func()

What does "binding on extraction mean"?

Articles I found that are relevant are:

Upvotes: 3

Views: 58

Answers (2)

meriton
meriton

Reputation: 70574

Imagine you had some class:

class C {
  foo() {
    console.log(this);
  }
}

and somebody does:

const c = new C();
const o = {
  callback: c.foo // "extract the function"
}
o.callback();

Which object should be logged to the console? c, because it originally declared the method, or o because that's what we specified at the call site?

JavaScript defaults to the latter, but you can achieve the former by calling Function.prototype.bind.

That is, the question they were discussing was whether class methods should automatically bind to this when being retrieved from an object, ensuring that this always refers to the object the method originally came from, as opposed to the object the caller uses to make the call.

Upvotes: 0

David784
David784

Reputation: 7464

Extraction basically means disconnecting the method from the object. You do this any time you call the method without "chaining" it to the class instance.

class Test {
  constructor(r) {
    this.r = r;
  }
  sample() {
    console.log(this);
  }
}

let t = new Test(1);
t.sample();
let q = t.sample;
q();

So in this example, when I call t.sample(), it returns exactly what I expect: { r:1 }. But when I set q = t.sample and then invoke q(), I get undefined. I've "extracted" my function and assigned it to a different variable.

This same thing happens if you use the function as an event handler.

Upvotes: 5

Related Questions