Reputation: 11524
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:
https://esdiscuss.org/topic/why-are-es6-class-methods-not-automatically-bound-to-the-instance - This is the article that generated my question. Search for "we could still have had methods bind on extraction"
Why aren't methods of an object created with class bound to it in ES6? - this is the Stack Overflow question and answer that references the article in question.
Mozilla MDN web docs on Classes - Strangely enough, the Rectangle example given as an example Javascript class doesn't use bind(). I'm guessing because it was so simple bind wasn't needed, but if it had, it would help the folks (like myself) that came to Javascript from a Java background
ES6 In Depth: Classes - very good article on prototype objects and how the class keyword is syntactic sugar.
Upvotes: 3
Views: 58
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
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