Skip to content

Instantly share code, notes, and snippets.

@XoseLluis
Created June 13, 2020 09:44
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/75c63a41dff31340a30083b1fc4cf691 to your computer and use it in GitHub Desktop.
Save XoseLluis/75c63a41dff31340a30083b1fc4cf691 to your computer and use it in GitHub Desktop.
Lazy Object via Proxy
//Create a Proxy for the lazy construction of an object
function buildLazyObject(constructorFn, ...args){
let internalObject = null;
//we don't care about the target, but compiler does not allow a null one, so let's pass an "empty object" {}
return new Proxy({}, {
get: function(target, property, receiver){
console.log("this === receiver " + (this === receiver)); //false
//"this" is not the proxy, but the handler object containing the traps (obviously are not the same object)
internalObject = internalObject || (() => {
console.log("Creating object");
return new constructorFn(...args);
})();
//this way, if it's a method, internal calls to other methods of the class would go through the proxy also
//for this case it makes no sense
//return internalObject[property];
let item = internalObject[property];
if (typeof(item) === "function"){
return function(...args){
return item.call(internalObject, ...args);
};
}
else{
return item;
}
},
set: function(target, property, value, receiver){
internalObject = internalObject || (() => {
console.log("Creating object");
return new constructorFn(...args);
})();
internalObject[property] = value;
}
});
}
//--------------------------------------------
class Person{
constructor(name, age){
this.name = name;
this.age = age;
}
sayHello(){
return "Bonjour, Je suis " + this.name + " et j'ai " + this.age + ", ma ville est " + (this.city || "inconnu");
}
}
let p1 = buildLazyObject(Person, "Francois", 2);
console.log("Proxy created");
console.log(p1.sayHello());
console.log("Second call");
console.log(p1.sayHello());
let p2 = buildLazyObject(Person, "Didier", 4);
console.log("Proxy created");
p2.city = "Marseille";
console.log("after set value");
console.log(p2.sayHello());
// Proxy created
// this === receiver false
// Creating object
// Bonjour, Je suis Francois et j'ai 2, ma ville est inconnu
// Second call
// this === receiver false
// Bonjour, Je suis Francois et j'ai 2, ma ville est inconnu
// Proxy created
// Creating object
// after set value
// this === receiver false
// Bonjour, Je suis Didier et j'ai 4, ma ville est Marseille
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment