Created
June 13, 2020 09:44
-
-
Save XoseLluis/75c63a41dff31340a30083b1fc4cf691 to your computer and use it in GitHub Desktop.
Lazy Object via Proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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