Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any chance to get the outer scope in Proxy?

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.

like image 223
Valary o Avatar asked Oct 31 '25 07:10

Valary o


1 Answers

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!";
like image 151
ibrahim mahrir Avatar answered Nov 01 '25 22:11

ibrahim mahrir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!