2

I am Proxing an object in a custom class and I'd like to get access to the methods and properties of that same class within my Proxy Object. Is it possible?

I thought there is a way to bind the context but it didn't work for me neight with apply, call nor bind.

Any suggestions would be appreciated!

class MyClass {
  constructor() {
    this.state = new Proxy(this.initialState, {
      set(target, prop, value) {
        // some logic goes here              
      }
    })
  }

  methodIneedToReach() {}

}

I need it to structure the code and prevent the mess.

ibrahim mahrir
  • 28,583
  • 5
  • 34
  • 61
Valary o
  • 407
  • 3
  • 16

1 Answers1

3

Either store the value of this in a variable called that for example and use that.methodIneedToReach inside the set method, or, better yet, use an arrow function for set. Since arrow functions don't have their own this keyword, they will use the surrounding one which is, in this case, the instance of your class:

class MyClass {
  constructor() {
    this.state = new Proxy(this.initialState, {
      set: (target, prop, value) => {                     // set is an arrow function
        this.methodIneedToReach();                        // works because 'this' inside here points to your class
      }
    })
  }

  methodIneedToReach() {}
}

Demo:

class MyClass {
  constructor() {
    this.initialState = { message: "Hello World!" };
  
    this.state = new Proxy(this.initialState, {
      set: (target, prop, value) => {
        this.methodIneedToReach();
      }
    })
  }

  methodIneedToReach(value) {
    console.log("'methodIneedToReach' is called");
  }
}

let inst = new MyClass();
inst.state.message = "Bye world!";
ibrahim mahrir
  • 28,583
  • 5
  • 34
  • 61