0

I'm confused. How I was able to save a new method to the Test class using this.outer? I didn't think this in this.wrap(3) would have a value at that time.

https://codesandbox.io/s/beautiful-hopper-on7zhs?file=/src/index.js

class Test {
  x = 1;

  addX(i) {
    return i + this.x;
  }

  wrap(i) {
    return () => this.addX(i);
  }

  howDoesThisWork = this.wrap(3);
}

const t = new Test();
console.log(t.howDoesThisWork()); // prints 4
j08691
  • 204,283
  • 31
  • 260
  • 272
bgoosman
  • 707
  • 4
  • 13
  • 1
    Instance variable declarations are treated as if they occur in the constructor function. Thus `this.wrap(3)` effectively happens in the constructor, creating `this.howDoesThisWork` and initializing it. – Pointy Jun 02 '23 at 15:58
  • See https://stackoverflow.com/questions/57608525/what-are-class-fields-in-javascript – Andrew Parks Jun 02 '23 at 15:58
  • Also https://github.com/tc39/proposal-class-fields – Andrew Parks Jun 02 '23 at 16:00
  • `x` and `howDoesThisWork` are [*public class field definitions*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields). They're processed in source code order at the beginning of the constructor (just after the call to `super`, if it's a subclass), and since they're processed in the constructor, `this` refers to the instance being constructed. (You don't have an explicit constructor, so one is created for you.) – T.J. Crowder Jun 02 '23 at 16:00
  • Thanks all! `Thus this.wrap(3) effectively happens in the constructor` – bgoosman Jun 02 '23 at 16:08

0 Answers0