Last active
October 15, 2020 01:59
-
-
Save mmichlin66/46257804ef630a2850dda2fa9193b2e4 to your computer and use it in GitHub Desktop.
Virtualizing TypeScript Properties with Proxy and Decorator - listing 4
This file contains hidden or 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
export function virtual( target: any, name: string) | |
{ | |
// symbol to keep the proxy handler value | |
let sym = Symbol( name + "_proxy_handler"); | |
Object.defineProperty( target, name, { | |
enumerable: true, | |
get() | |
{ | |
// get the proxy from the handler | |
return this[sym]?.proxy; | |
}, | |
set(v) | |
{ | |
// check whether we already have the handler and created it if we don't | |
let handler = this[sym]; | |
if (!handler) | |
this[sym] = handler = new VirtHandler(); | |
// create a new proxy each time because we want the proxy to have the new value. | |
handler.proxy = new Proxy( v, handler); | |
// set the new vaule to the handler so that it will use it from now on | |
handler.target = v; | |
} | |
}); | |
} | |
class VirtHandler | |
{ | |
target: any; | |
get( t: any, p: PropertyKey, r: any): any | |
{ | |
return this.target[p]; | |
} | |
} |
This file contains hidden or 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
class Base | |
{ | |
@virtual first = { v: 1 }; | |
second = this.first; | |
} | |
class Derived extends Base | |
{ | |
first = { v: 2 }; | |
} | |
let obj = new Derived(); | |
console.log( obj.second.v); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment