0

This might be a weird use case with no solution, but I would be happy to hear any answers on how to solve it.

Question:

I have a globally defined proxy:

this.appState = {}
global.globalState = new Proxy(this.appState, {
  get: (target, prop, receiver) => {
    console.log(this) // #3
    return Reflect.get(...arguments)
  },
  set: (obj, prop, value) => {
    console.log(this) // #2
    obj[prop] = value
    return true
  }
})

And somewhere else I have a class:

export default class MyClass {
  constructor() {
    console.log(this) // #1
    global.globalState["greet"] = "hi"
    console.log(this.globalState["greet"])
  }
}

Is it possible to bind this from the class constructor to be also this in getter and setter of the proxy? So basically, the context of the class constructor needs to be accessed from inside of the proxy getter and setter.

4
  • Are these two pieces of code in same file? Are they in same class, cus I see ` this` in the first piece, does it points to MyClass instance? Commented Mar 27, 2021 at 1:02
  • @hackape That is what the question is... if it's possible to bind the class to the Proxy this. The current ones are the proxy instance Commented Mar 27, 2021 at 1:04
  • Yes sure. Wrap the proxy creation into a function, then .call it with new MyClass Commented Mar 27, 2021 at 1:05
  • @JonasWilms this is not exactly what I want. The proxy is created globally on sort of boot. It also will be accessed from multiple classes so creating it in a specific class is not going to work. Commented Mar 27, 2021 at 1:12

1 Answer 1

1

If your question is wether the line

global.globalState["greet"] = "hi"

can be somehow modified to change the this in the Proxies get method, then the answer is no. The arrow function is lexically bound (so its this can't change between different calls), and even if you would use a regular function instead there is still no way to call it by assigning a property, as the function is called by the runtime, and as Proxies are transparent, there is no way to influence that at all (you don't even know that the line calls a setter).


To dynamically change this you could use something like:

 let context = null;

 // inside the getter
 (function thisInjection() {

 }).call(context);

however that would require modifying the Proxies code, and in that case replacing this with context would be way easier.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, I see how it works. I just needed to hear that it is not possible because I spent some time hacking around it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.