top | item 44455943

(no title)

JoeOfTexas | 8 months ago

There is a bit more nuance in using `this` in a named function that wasn't covered. Named functions defined in classes are scoped outside of the class, meaning they are not bound to the class. To use `this` in your named function, you usually have to bind it in the constructor using `this.functionName.bind(this)`

Arrow functions defined within a class are scoped and bound to the class automatically. Hence, arrow functions do not require calling the .bind in constructor, and you can happily use `this` inside arrow functions.

discuss

order

moritzwarhier|8 months ago

The article misses even more nuance, independent from classes.

If you define

  const o = { a: "Hello", b() { return this.a;} }
then

  o.a()

will return "Hello"

while

  const b = o.b; // not a.b ...
  b();

will throw an error.

This predates generator functions and classes (which are only syntax sugar AFAIK).

And it seems like a glaring omission giving the submission title.

I'm ashamed though if it's in there and I missed it.

The behavior is called "late binding".

WorldMaker|8 months ago

Late binding is also what the above poster is complaining about and they mention the habit some have in class constructors for "early binding" to try to avoid it.

postalrat|8 months ago

Of course it's an error. 'a' isn't defined.