Skip to content

Instantly share code, notes, and snippets.

@XoseLluis
Created July 14, 2016 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XoseLluis/f4d83ffeeae50bf823a174b51bc7e113 to your computer and use it in GitHub Desktop.
Save XoseLluis/f4d83ffeeae50bf823a174b51bc7e113 to your computer and use it in GitHub Desktop.
//http://blog.keithcirkel.co.uk/metaprogramming-in-es6-part-2-reflect/
//http://stackoverflow.com/a/25585988
function runTest(account){
console.log("___________");
console.log(account.totalSpent);
console.log("-----------");
console.log(account.amountAvailable);
console.log("-----------");
console.log("toString: " + account.toString());
console.log("___________");
}
let account = {
initialAmount: 300,
spentInBooks: 0,
spentInOtherStuff: 0,
toString(){
return `${this.initialAmount} | ${this.spentInBooks} , ${this.spentInOtherStuff}`;
}
};
Object.defineProperty(account, "totalSpent", {
get: function () {
return this.spentInBooks + this.spentInOtherStuff;
}
});
Object.defineProperty(account, "amountAvailable", {
get: function () {
return this.initialAmount - this.totalSpent;
}
});
account.spentInBooks = 10;
account.spentInBooks = 15;
//Do not go through the proxy for internal calls (neither for methods nor descriptor accessors)
var proxiedAccount1 = new Proxy(account, {
//target is the object being proxied
get: function(target, propKey, receiver){
console.log("intercepting call to " + propKey );
var propValue = target[propKey];
if (typeof propValue != "function"){
return Reflect.get(target, propKey); // === Reflect.get(target, propKey, target)
}
else{
return function(){
return propValue.apply(target, arguments);
}
}
}
}
);
runTest(proxiedAccount1);
console.log("");
//Go through the proxy for internal method calls and internal accessor descriptors
var proxiedAccount2 = new Proxy(account, {
//target is the object being proxied
get: function(target, propKey, receiver){
console.log("intercepting call to " + propKey );
return Reflect.get(target, propKey, receiver);
}
}
);
runTest(proxiedAccount2);
console.log("");
//internal method calls will also go through the proxy, but not the accessor descriptors
var proxiedAccount3 = new Proxy(account, {
//target is the object being proxied
get: function(target, propKey, receiver){
console.log("intercepting call to " + propKey );
return Reflect.get(target, propKey); // === Reflect.get(target, propKey, target)
}
}
);
runTest(proxiedAccount3);
console.log("");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment