User Tools

Site Tools


js:metaproxy

Advanced Proxy Class in JavaScript

The Proxy Class in ES6 is a nice thing if you want to create somewhat abstract code for this or another Reason. When it comes to complex Data-Interfaces you gotta love this class. It never had been easier to wrap Binary Data or Database Access together. But the whole thing has one flaw. At least I see it as flaw.

How to change the target on JS Proxy Instances?

In some cases you just _need_ to change an proxys target. For example if you want to reload code at runtime and update running object instances. In order to keep all references valid you need the Proxy class. But this on the other hand needs you to change its target.

Solution

class Mirror {
  constructor(target) {
    this.ref = target;
  }
 
  get(target, name, receiver) {
    if(name=='__target')
      return this.ref;
    return this.ref[name];
  }
 
  set(target, name, value, receiver) {
    if(name=='__target')
      return this.ref = value;
 
    return this.ref[name] = value;
  }
};
 
function MetaProxy(target) {
  return new Proxy(target, new Mirror(target));
}
 
module.exports = MetaProxy;

Limitations

Unfortunatly the whole thing has Limitations (thats why I had not posted it as npm): Many JavaScript Engines cache object references, and there is no way to avoid it.

let a = new Point(5,5);
console.log(a);  // Point(5,5)
 
let p = MetaProxy(a);
console.log(p);  // Point(5,5)
 
let b = new Point(10,10);
p.__target = b;
 
console.log(p);  // Point(5,5)
console.log(p.x);  // 10
console.log(p.y);  // 10
console.log(p.toString());  // Point(10,10)
console.log(p.__target);    // Point(10,10)

Why is that so? Well, the Proxy does not passes thought the main reference. Just the child-attributes will be affected.

Conclusion

Well. This solution works whenever you work with proxys and you _know_ doing so. For my purposes this was enought.

js/metaproxy.txt · Last modified: 2016/11/10 10:12 (external edit)