Proxy Data Synchronization
Proposal for vAnalyze
by danShumway
JavaScript
//Setup
X.prototype = { constructor:X, b:'b' };
function X() {
this.a = 'a';
}
var x = new X();
//Create infection and attach to host. Normally host properties would be wrapped in getters here as well.
var infection = {}, host = x;
var p = new Proxy(infection, {
get : function(target, name, reciever) {
if(host.hasOwnProperty(name)) {
infection[name] = host[name]; //And log that at some point the original was updated.
return host[name];
} else {
return infection[name];
}
},
set : function(target, name, value) {
infection[name] = value; //And similarly log stuff.
host[name] = value;
}
});
infection.__proto__ = host.__proto__;
host.__proto__ = infection;
//Make infection invisible
Object.defineProperty(host, '__proto__', {
enumerable: false,
get: function(){ return infection.__proto__; },
set: function(value){ infection.__proto__ = value; }
});
Object.defineProperty(host, '__infection__', { //Maybe unecessary?
enumerable: false,
value: p
});
//TODO: Hook around Object.getPrototype() and setPrototype()
Object.getPrototypeOf = function(obj) {
return obj.__proto__;
}
Object.setPrototypeOf = function(obj, value) {
obj.__proto__ = value;
}
//Testing
console.log('Proxy: ', p.a, 'Proxy prototype: ', p.b, ' Original: ', x.a, 'Original prototype: ', x.b);
p.a = 'changed via proxy';
console.log('Proxy edit: ', p.a, ' Original reference: ', x.a);
x.a = 'changed on original';
console.log('Proxy reference: ', p.a, ' Original edit: ', x.a);
console.log('x instanceof X', x instanceof X);
console.log('Proxy instanceof X', p instanceof X);
console.log('Object prototype === Proxy prototype === X.prototype', x.__proto__ === p.__proto__ && x.__proto__ === X.prototype);
p.__proto__ = { b:'new' };
console.log('Prototype can be mutated on Proxy: ', p.__proto__, x.__proto__);
x.__proto__ = { b:'newer' };
console.log('Prototype can be...