Skip to content

Instantly share code, notes, and snippets.

@gdhardy1
Created November 17, 2020 23:20
Show Gist options
  • Save gdhardy1/690e230a33a04ea153ca3912a274f9f2 to your computer and use it in GitHub Desktop.
Save gdhardy1/690e230a33a04ea153ca3912a274f9f2 to your computer and use it in GitHub Desktop.
JS Proxy
// Example of Proxy in JS
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
class Target{
log(msg){
console.log(msg)
return msg
}
}
const target = new Target()
const handler = {
get: (target, name, receiver)=>{
return (...args)=>{
if (typeof target[name] === 'function') {
console.log(`Proxied! ${target[name](...args)}`)
}else{
return Reflect.get(target, name, receiver)
}
}
}
}
const myProxy = new Proxy(target, handler)
// myProxy.log("This")
// myProxy.log(1)
const validator ={
get: (target, name, receiver)=>{
return (...args)=>{
if(name === "log" && typeof(args[0]) !== String ){
console.log(`Error: Must provide a string!`)
}
}
}
}
const validatedProxy = new Proxy(myProxy, validator)
validatedProxy.log("asdfasd")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment