-2

class Field1 {
  data = 0;
  constructor(init) {
    this.data = init;
  }
}

class Field2 {
  data = 0;
  constructor(init) {
    this.data = init;
  }
}

class Field3 {
  data = 0;
  constructor(init) {
    this.data = init;
  }
}

class Test {
  field1 = new Field1(1);
  field2 = new Field2(2);
  field3 = new Field3(3);

  constructor() {
    this.compose2(this.func1, this.func2, this.func3);
  }

  func1() {
    console.log("init func1");
    console.log(this.field1.data);
  }
  func2() {
    console.log("init func2");
    console.log(this.field2.data);
  }
  func3() {
    console.log("init func3");
    console.log(this.field3.data);
  }
  compose2(...args) {
    console.log(args);

    args.reduce(
      (prevFunc, nextFunc) => {
        nextFunc();
      },
      (init) => init
    );
  }
}

new Test();

Inside the func1, func2, func3 functions, class fields named field1, field2, field3 is not accessible. I get error message saying "Cannot read properties of undefined (reading 'field1')". I assume it is because Class syntax. Because it works find without class.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • Why did you create 3 classes with the same code? Use a single `Field` class and instantiate it thrice! – Bergi Mar 21 '23 at 03:46

1 Answers1

-1

You need to set the this context, which can be done with Function#call.

nextFunc.call(this);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80