Created
July 3, 2021 20:20
-
-
Save dfoverdx/78a6bf63a8c79e292953ee6674877bf0 to your computer and use it in GitHub Desktop.
Add an isProxy property to Proxies
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
// Note to anyone who just happened upon this: I am not proud of this code. | |
Symbol.isProxy = Symbol('@@isProxy'); | |
const _Proxy = Proxy; | |
(typeof global === 'undefined' ? window : global).Proxy = new _Proxy(_Proxy, { | |
construct(target, args, newTarget) { | |
const result = Reflect.construct(target, args, newTarget); | |
return new _Proxy(result, { | |
get(target, prop, receiver) { | |
if (prop === Symbol.isProxy) { | |
return true; | |
} | |
return Reflect.get(target, prop, receiver); | |
} | |
}); | |
// Alternatively if you would rather require the user to handle the @@isProxy symbol, you can avoid returning a proxied Proxy. | |
Object.defineProperty(result, Symbol.isProxy, { | |
get() { return true; } | |
}); | |
return result; | |
} | |
}); | |
const add1Proxy = new Proxy({ two: 1 }, { | |
get(t, prop, receiver) { | |
return Reflect.get(t, prop, receiver) + 1; | |
} | |
}); | |
console.log(add1Proxy.two); | |
console.log(add1Proxy[Symbol.isProxy]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment