(I've been informed by Stack Overflow that this question is likely to be downvoted or marked as duplicate, but I'd ask you not to, as I've been poring through Stack Overflow answers to try to answer it and found posts that say conflicting things, which is what I'm trying to resolve).
I'm trying to understand the binding of arrow functions (as well as how that relates to their use as object and class methods). My understanding is that an arrow function is bound at the moment of creation, taking this
from the context in which it is defined. Some posts say that this is so. Some posts say the opposite, maintaining that a arrow function is simply not bound, such as this post, Arrow Functions and This , where the most highly-voted answer says:
Short answer: this points at the nearest bound this - in the code provided this is found in the enclosing scope.
Longer answer: Arrow functions
bind their this when they are createddo not have this, arguments or other special names bound at all - when the object is being created the name this is found in the enclosing scope, not the person object.
I created a small Codepen example to test out which is correct, and I believe that indeed, arrow functions are bound permanently when created: if you assign an arrow function to a property of an object then call that function in the context of another object, it still maintains the this
it had when it was created.
Which is it? Are arrow functions bound permanently at creation to the this
of the context in which they were created, or not bound at all?
If they are indeed bound when created, is that the reason you can use an arrow function as a method in an ES6 class? That is to say in this case
class MyClass {
constructor() {
this.myVariable = 0;
console.log("in constructor this is",this)
this.myMethod = () => {
console.log("in myMethod this is",this)
this.myVariable++;
};
}
the arrow function myMethod is simply bound to the this
which the constructor has defined as the context for the instance being created?
Thanks for any help!