Tim Nimets
Tim Nimets

Reputation: 364

JavaScript binding Proxy getters/setters to a specific context

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.

Upvotes: 0

Views: 744

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138277

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.

Upvotes: 1

Related Questions